PDA

View Full Version : images/directory listing script



djr33
10-18-2006, 07:11 AM
I could write this myself, but it would take a while.

Is there an existing script to check a directory for inner directories and images and display links to them?

GD scaled thumbnail preview would be awesome, but probably more than I could hope to find.

tech_support
10-18-2006, 07:20 AM
http://www.phpxplorer.org/phpXplorer/webIndex.php

djr33
10-18-2006, 07:39 AM
Very interesting and thanks.
However, that's more than I need.
I just want images and directories, with, perhaps an image preview. But not something that complex.

I might be able to use it if I don't find an alternate.

Strangeplant
10-18-2006, 12:33 PM
<?php
/* ================================================================
== Directory Contents Listing of Compressed Raw Lidar Data Files ==
== DirSelect.php ==
== Lists only WinRAR files - line 60 ==
== Install as /webmail/apache/htdocs/noaa/wc/LidarArk/index.php ==
== Uses /webmail/apache/htdocs/noaa/wc/LidarArk/lib/style.css ==
== Tom Legbandt 08/15/06 ==
=================================================================*/
function _begin_ahtml()
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<link rel="STYLESHEET" type="text/css" href="lib/style.css">
<title>Raw Lidar Data Archive</title>
</head>
<body>
<?
}
function _page_atop()
{
?>
<div style="text-align: center; color: rgb(102, 102, 102);"><b>
<span style="font-size: 20pt; font-family: Microsoft Sans Serif; color: #808000;">WEATHER CENTER RAW LIDAR DATA ARCHIVE</span><br>
<span style="font-size: 16pt; font-family: Trebuchet MS; color: gray;">The City College of New York</span><br>
<span style="font-size: 10pt; font-family: Trebuchet MS; color: #808000;">138th Street &amp; Convent Avenue, New York, NY 10031<br><br></span></b>
</div>
<?
}
function _end_ahtml()
{
?>
<p align="center">For additional files you may need that are not listed, contact <a href="mailto: weatherman@ee.ccny.cuny.edu">weatherman</a></p>
</body>
</html>
<?
}

include_once("inc/auth.inc.php");
$user = _check_auth($_COOKIE);
$myFile = "/webmail/apache/htdocs/noaa/wc/Logs/DataAccess.log";
$fh = fopen($myFile, 'a') or die('cannot open file');
$stringData = date("Y/m/d H:i:s")." ".$user['user_name']." ".$_SERVER['REMOTE_ADDR']." ".$_SERVER['SCRIPT_FILENAME']."\n";
fwrite($fh, $stringData);
fclose($fh);
$dir = ".";
$directories = array();
$files = array();
$dir = (substr($dir, -1) == '/') ? substr($dir, 0, -1) : $dir;
if(is_dir($dir)){
if($handle = opendir($dir)){
while(false !== ($file = readdir($handle))){
if($file != "." && $file != ".."){
if(is_dir($dir.'/'.$file)){
$directories[$file] = filemtime($dir.'/'.$file);
} else {
if(strpos($file, '.rar') !== false) $files[$file] = filemtime($dir.'/'.$file);
}
}
}
closedir($handle);
} else {
die('Could not open directory.');
}
} else {
die('Invalid directory.');
}

if($_GET['sort'] == 'alpha'){
if($_GET['mode'] == 'desc'){
krsort($files);
$highlight = 'alpha_desc';
} else {
ksort($files);
$highlight = 'alpha_asc';
}
} else {
if($_GET['mode'] == 'asc'){
asort($files, SORT_NUMERIC);
$highlight = 'date_asc';
} else {
arsort($files, SORT_NUMERIC);
$highlight = 'date_desc';
}
}
$sort_alpha_asc = ($highlight == 'alpha_asc') ? '<b>Asc</b>' : '<a href="?sort=alpha&mode=asc">Asc</a>';
$sort_alpha_desc = ($highlight == 'alpha_desc') ? '<b>Desc</b>' : '<a href="?sort=alpha&mode=desc">Desc</a>';
$sort_date_asc = ($highlight == 'date_asc') ? '<b>Asc</b>' : '<a href="?sort=date&mode=asc">Asc</a>';
$sort_date_desc = ($highlight == 'date_desc') ? '<b>Desc</b>' : '<a href="?sort=date&mode=desc">Desc</a>';
_begin_ahtml();
_page_atop();
echo "<center><p>Sort by: Date- $sort_date_asc | $sort_date_desc; Name- $sort_alpha_asc | $sort_alpha_desc</p></center>\n";

echo "<center><table border=\"0\">\n<tr><td><u>File</u></td><td width=\"25\"></td><td><u>Size</u></td><td width=\"25\"></td><td><u>Last Modified</u></td></tr>\n";
foreach($files as $file => $timestamp){
echo "<tr><td><a href=\"$dir/$file\">$file</a></td><td></td><td>";
$filesize = filesize($dir.'/'.$file);
if($filesize >= 1048576){
echo round($filesize / 1048576, 1).'MB';
} else {
echo round($filesize / 1024, 1).'kb';
}
echo '</td><td></td><td>'.date('M d Y H:i:s', $timestamp)."</td></tr>\n";
}
echo '</table></center>';
_end_ahtml();
?>
You can take out this block of code for my password login and user tracking and put in your own controls, if any:
include_once("inc/auth.inc.php");
$user = _check_auth($_COOKIE);
$myFile = "/webmail/apache/htdocs/noaa/wc/Logs/DataAccess.log";
$fh = fopen($myFile, 'a') or die('cannot open file');
$stringData = date("Y/m/d H:i:s")." ".$user['user_name']." ".$_SERVER['REMOTE_ADDR']." ".$_SERVER['SCRIPT_FILENAME']."\n";
fwrite($fh, $stringData);
fclose($fh);
Once you have the file names and links, you can do anything you want with them. Change the file type(s) you want to list/display at line 60.

Twey
10-18-2006, 07:47 PM
Woah Nelly :eek: Here's a lighter-weight solution to the same problem (not that anything is wrong with yours, Strangeplant):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Directory Listing</title>
<style type="text/css">
ul.dirlist, ul.dirlist li {
list-style-type: none;
padding-left: 1em;
}
</style>
</head>
<body>
<?php
$cwd = $_SERVER['REQUEST_URI'];
$cwd = substr($cwd, 0, strrpos($cwd, '/' + 1));

function paintUndersideOfFox($c) {
echo('<ul class="dirlist">');
$d = opendir($c);
while($f = readdir($d)) {
if(strpos($f, '.') === 0) continue;
$ff = $c . '/' . $f;
echo('<li><a href="' . $cwd . $ff . '">' . $ff . '</a></li>');
if(is_dir($ff)) paintUndersideOfFox($ff);
}
echo('</ul>');
}

paintUndersideOfFox('.');
?>
</body>
</html>

djr33
10-18-2006, 10:29 PM
Thanks, Twey.
And thanks Strangeplant. I'm sure your solution is fine too... less text is just easier. But thanks for all the wok :)

Twey, I love your odd function names.

I'll use this now...


The more I look at it, Strangeplant's solution does offer quite a few more features, like filesize, filetype, etc.
Interesting.

Strangeplant
10-19-2006, 01:04 PM
And sorting.....

djr33
10-19-2006, 01:45 PM
I just did some modifications to the script (Twey's).

Strangeplant, the main thing that didn't work about your script was that it didn't include subdirectories. Twey's did that, so I could base what I did off of his.

So... here's what I ended up with.

I'd consider submitting to DD, assuming Twey is ok with it (I'd assume so, since he just wrote it up for this, from the looks of it.) Let me know what you think.

Not promising the code isn't messy... but it works.

This is the displaying page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Image Browser</title>
<style type="text/css">
ul.dirlist, ul.dirlist li {
list-style-type: none;
padding-left: 20;
}
a {
color: #0000FF;
}
</style>
</head>
<body bgcolor="#000000" text="#0000FF">
<?php
$page = substr($_SERVER['SCRIPT_NAME'],(strrpos($_SERVER['SCRIPT_NAME'],"/")+1));
function checkDir($c,$skipimages=0) {
echo('<ul class="dirlist">');
$d = opendir($c);
while($f = readdir($d)) {
if(strpos($f, '.') === 0) continue;
$ff = $c . '/' . $f;
if (strpos(strtolower($f), '.jpg') !== FALSE && $skipimages != 1) {
$fff = '<img src="thumbnail.php?image='.urlencode($ff).'" border="">';
echo('<a href="' . $ff . '">' . $fff . '</a>'."\n");
}
if(is_dir($ff)) {
$ffdisp = $ff;
if (substr($ff,0,2) == "./") $ffdisp = substr($ffdisp,2);
echo '<li><a href="'.$page.'?'.urlencode($ffdisp).'"'.">$ffdisp</a></li>\n";
global $dir;
if ($ff == $dir) $skipimages = 0;
else $skipimages = 1;
checkDir($ff,$skipimages);
}
}
echo("</ul>");
}

$uri = explode("?",$_SERVER['REQUEST_URI'],2);
$dir = urldecode($uri[1]);
if(is_dir($dir)) {
checkDir($dir);
if(strpos($dir,"/") !== FALSE) {
$updir = "?".substr($dir,0,strrpos($dir,"/"));
echo '<a href="'.$page.$updir.'">^up^</a><br>'."\n";
}
echo '<a href="'.$page.'">Images Main</a>'."\n";
}
else checkDir(".");
?>
</body>
</html>
thumbnail.php (required)
<?php
// The file
if ($_GET['image'] == "") die('Image Does Not Exist');
$filename = urldecode($_GET['image']);

// Set a maximum height and width
$width = 200;
$height = 200;


// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);


// Content type
header('Content-type: image/jpeg');
// Output
imagejpeg($image_p, null, 30);

?>thumbnail.php is just cut and paste from php.net's page on the imagecopyresampled() filter, plus changes in the top couple lines to include the get functions. I also moved the header down, 'cause that made sense.

The CSS/layout is customized to my site, but it's clean and shouldn't look too bad for others.

Test page:
http://ci-pro.com/truthandlies/images/
(This is for my current movie project. It has a bunch of images, mostly in the lowest level folders, but some in the middle ones. The script would work fine if they were in the top level, etc. as well.)


Problems:
1. There's a slight lag, especially with a lot of images. The GD rendering of the thumbnails is obviously server intensive. It isn't all that much slower, though, than loading the images would be anyway, and certainly not as slow as if the full size images were included with small height/width attributes and the whole image had to load.
2. I would like to display the number of images in a directory that isn't selected. This isn't crucial, but seems like the nice little piece that's missing. I did this, but it was a problem because I did it backwards.... the number was only available after the line with the link had been output.
3. It only works with JPGs. Not too hard to fix, but that's all I needed. That can be updated soon.

4. Just found an error. Images in a folder with subdirectories don't display. I'll figure this out tomorrow. For now, sleep. (It worked earlier. Something must be in conflict now.)

Twey
10-19-2006, 07:36 PM
1. There's a slight lag, especially with a lot of images. The GD rendering of the thumbnails is obviously server intensive. It isn't all that much slower, though, than loading the images would be anyway, and certainly not as slow as if the full size images were included with small height/width attributes and the whole image had to load.Render them once and store them to a file. Much more efficient.

djr33
10-19-2006, 09:52 PM
Yeah, that's possible.

But I'm not looking to create a static image gallery.
I want this to be versatile and expand with new images added (or deleted).


Also, just realized a major design flaw... the directories are full, in the way that it's structed now.... it displays the full path as the link to the subdirectory.
I'm going to change that so that it is nice and just displays the last subdirectory, for easier navigation. I knew something was wrong with the layout.

djr33
10-19-2006, 11:28 PM
UPDATE:
(The code for thumbnails.php is the same, and still required. See above.)


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Image Browser</title>
<style type="text/css">
ul.dirlist, ul.dirlist li {
list-style-type: none;
}
a {
color: #0000FF;
}
div.border {
border-left-style: solid;
border-bottom-style: solid;
border-color: #000066;
border-width: thin;
}
</style>
</head>
<body bgcolor="#000000" text="#0000FF">
<?php
$page = substr($_SERVER['SCRIPT_NAME'],(strrpos($_SERVER['SCRIPT_NAME'],"/")+1));
function checkDir($c,$skipimages=0) {
echo('<div class="border"><ul class="dirlist">');
$d = opendir($c);
while($f = readdir($d)) {
if(strpos($f, '.') === 0) continue;
$ff = $c . '/' . $f;
if (strpos(strtolower($f), '.jpg') !== FALSE && $skipimages != 3) {
if ($skipimages != 1) {
$fff = '<img src="thumbnail.php?image='.urlencode($ff).'" border="">';
echo('<a href="' . $ff . '">' . $fff . '</a>'."\n");
}
else {
$n++;
}
}
if(is_dir($ff)) {
$fflink = $ff;
if (substr($ff,0,2) == "./") $fflink = substr($ff,2);
echo '<li><a href="'.$page.'?'.urlencode($fflink).'"'."><b>$f</b></a></li>\n";
global $dir;
if ($ff == $dir) $skipimagesnext = 0;
else $skipimagesnext = 1;
if ($skipimages == 2) $skipimagesnext = 2;
if ($skipimages == 3) $skipimagesnext = 3;
checkDir($ff,$skipimagesnext);
}
}
if ($n != "") echo "($n images)\n";
echo('</ul></div>');
}

$uri = explode("?",$_SERVER['REQUEST_URI'],2);
$dir = urldecode($uri[1]);
if(is_dir($dir)) {
checkDir($dir);
if(strpos($dir,"/") !== FALSE) {
$updir = "?".substr($dir,0,strrpos($dir,"/"));
echo '<a href="'.$page.$updir.'">^up^</a><br>'."\n";
}
echo '<a href="'.$page.'">Top</a>'."\n";
}
else if($dir == "all") checkDir(".",2);
else if($dir == "none") checkDir(".",3);
else checkDir(".");
echo '<a href="'.$page.'?none">Collapse All</a>'."\n";
echo '<a href="'.$page.'?all">Expand All</a>'."\n";
?>
</body>
</html>

Updated test page: http://ci-pro.com/truthandlies/images/index.php

Everything works.
Images and subdirectories display within directories.
Added "expand all" and "collapse all" links.
Added numbers showing how many images a non-expanded subdirectory contains.
Did some work on the layout so it is visually clear. (And the numbers work now.)


No work on making the images pre-rendered. Not sure if this makes sense. (doing an if and checking if the image has an existing thumbnail and if not, creating one, seems like a bit much at the moment. Maybe....)

No support for non-jpegs. Not yet. Easy later, though.


I'm really liking it.

djr33
10-20-2006, 12:40 AM
Ok, now .jpg, .jpe, .jpg, .gif, and .png work, with easy addition for more filetypes, though I'm not sure what more would be supported by the GD library as is.
Index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Image Browser</title>
<style type="text/css">
ul.dirlist, ul.dirlist li {
list-style-type: none;
}
a {
color: #0000FF;
}
div.border {
border-left-style: solid;
border-bottom-style: solid;
border-color: #000066;
border-width: thin;
}
</style>
</head>
<body bgcolor="#000000" text="#0000FF">
<?php
$page = substr($_SERVER['SCRIPT_NAME'],(strrpos($_SERVER['SCRIPT_NAME'],"/")+1));
function checkDir($c,$skipimages=0) {
echo('<div class="border"><ul class="dirlist">');
$d = opendir($c);
while($f = readdir($d)) {
if(strpos($f, '.') === 0) continue;
$imagestypes = array(".jpg",".jpe",".jpeg",".gif",".png");
foreach (array(".jpg",".jpe",".jpeg",".gif",".png") as $imageext) {
if (strtolower(substr($f,(strlen($f)-strlen($imageext)))) == $imageext) {
$imageextok = 1;
break;
}
} $ff = $c . '/' . $f;

if ($imageextok == 1 && $skipimages != 3) {
if ($skipimages != 1) {
$fff = '<img src="thumbnail.php?image='.urlencode($ff).'" border="">';
echo('<a href="' . $ff . '">' . $fff . '</a>'."\n");
}
else {
$n++;
}
}
if(is_dir($ff)) {
$fflink = $ff;
if (substr($ff,0,2) == "./") $fflink = substr($ff,2);
echo '<li><a href="'.$page.'?'.urlencode($fflink).'"'."><b>$f</b></a></li>\n";
global $dir;
if ($ff == $dir) $skipimagesnext = 0;
else $skipimagesnext = 1;
if ($skipimages == 2) $skipimagesnext = 2;
if ($skipimages == 3) $skipimagesnext = 3;
checkDir($ff,$skipimagesnext);
}
}
if ($n != "") echo "($n images)\n";
echo('</ul></div>');
}

$uri = explode("?",$_SERVER['REQUEST_URI'],2);
$dir = urldecode($uri[1]);
if(is_dir($dir)) {
checkDir($dir);
if(strpos($dir,"/") !== FALSE) {
$updir = "?".substr($dir,0,strrpos($dir,"/"));
echo '<a href="'.$page.$updir.'">^up^</a><br>'."\n";
}
echo '<a href="'.$page.'">Top</a>'."\n";
}
else if($dir == "all") checkDir(".",2);
else if($dir == "none") checkDir(".",3);
else checkDir(".");
echo '<a href="'.$page.'?none">Collapse All</a>'."\n";
echo '<a href="'.$page.'?all">Expand All</a>'."\n";
?>
</body>
</html>thumbnail.php
<?php
// The file
if ($_GET['image'] == "") die('Image Does Not Exist');
$filename = urldecode($_GET['image']);
foreach (array(".jpg",".jpe",".jpeg",".gif",".png") as $imageext) {
$extn++;
if (strtolower(substr($filename,(strlen($filename)-strlen($imageext)))) == $imageext) {
$imageextok = 1;
break;
}
}
if($imageextok != 1) die('Image Filetype Incorrect');

// Set a maximum height and width
$width = 200;
$height = 200;


// Get new dimensions
if (@getimagesize($filename)) list($width_orig, $height_orig) = getimagesize($filename);
else die('Image Filetype Incorrect.');

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}

// Make image

if ($extn == 1 || $extn == 2 || $ext ==3) {
if (@imagecreatefromjpeg($filename)) $image = imagecreatefromjpeg($filename);
}
else if ($extn == 4) {
if (@imagecreatefromgif($filename)) $image = imagecreatefromgif($filename);
}
else if ($extn == 5) {
if (@imagecreatefrompng($filename)) $image = imagecreatefrompng($filename);
}
if (!isset($image)) die('Image Filetype Incorrect.');


// Resample
$image_p = imagecreatetruecolor($width, $height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);


// Content type
header('Content-type: image/jpeg');
// Output
imagejpeg($image_p, null, 30);

?>

NOTE: Make sure that the lists (arrays) of filetypes match in both files, or there will be inconsistances.

blm126
10-20-2006, 01:04 AM
Instead of checking the extension why not use getimagesize()? It returns the image type also(despite the name).Why not cache the thumbnails? Use md5_file on the original and generate the thunmnail name off of that. Then only create a file if the hash isn't found.

djr33
10-20-2006, 01:14 AM
md5_file is a good idea. Interesting.
How about deleting old thumbnails if the images don't exist any more? That seems awfully hard to go about. Sure, not a huge issue. But... yeah.
I'll think about this.

getimagesize has filetype too? Intersting.
Looking at the function on php.net.... strange. But seems useful. I'll need to make it ignore PSD/SWF/etc.... but... cool.
I'll try to add that soon.

ItsMeOnly
10-21-2006, 06:45 PM
Gallery


<?php
$path = $_GET['path'];

/*sanity check for breakout attempt, plus remove if path gives... no path*/
if (($path == ".") || ($path == "/")) unset($path);
if (strpos($path, "/../") !== false ||
strpos($path, "../") === 0) $path = false;
if ($path) $path = stripslashes($path);

include "gallery.conf";
/* dangerous, uncomment when you know what you're doing
if (!isset($masterpath)) $masterpath = getcwd();
*/
include "messages.txt";
/* http://ftp.id.uw.edu.pl/pub/text/gallery/messages.txt */

include "$headername";

if (!is_dir("$masterpath/$path")) {
echo "
<div class=\"bigtitle\" style=\"text-align: center\">Directory unreadable</div>
<hr />
";
unset($path);
};

if ($path) {
$pwd = "$masterpath/$path";
if (dirname("$pwd") != $realpath) {
$link = "?path=".dirname("$path");
}
} else {
$pwd = $masterpath;
$link="";
}

$dir_handle = opendir("$pwd");

$f = 1; $d = 1;

for ($x = 1; $x < 2048; $x++) {
$element = readdir($dir_handle);
if (($element) && ($element != ".")) {
if (is_dir("$pwd/$element")) {
$dirs[$d] = $element;
$d++;
} else {
if (getimagesize("$pwd/$element"))
$files[$f] = $element;
$f++;
}
}
}

if ($files) {
sort($files);
reset($files);
}

if ($dirs) {
sort($dirs);
reset($dirs);
}

$d = 0; $f = 0;

$mypath = (isset($path)) ? "$path/" : "";

for ($x = 1; $x <= (sizeof($dirs) + sizeof($files)); $x++) {
unset($name, $filename, $title, $size, $mtime, $myname, $mywidth, $myheight, $dimensions, $status);


if ($dirs[$d] && (!$done)) {
/* what to do with parent dirs*/
if ($dirs[$d] == "..") {
$filename = "..";
$title = $goup;
$dirtype = $parentdir;
if ($path) $name = "document.location.href = '$link'";
else $name = ""; /* or real link outside gallery */
} else {
$name = "document.location.href = '?path=$mypath".addcslashes("$dirs[$d]", "\"\'")."'";
$title = $filename = $dirs[$d];
$dirtype = $directory;
}
$thumb = "dir.php";
$mtime = date ("Y:m:d G:i", filemtime("$pwd/$dirs[$d]"));
$myname = ($dirs[$d] == "..") ? basename(dirname("/var/ftp/pub/$path")) : addcslashes("$filename", "\'\"");
$d++;

$done = 0;
} else {
$done = 1;
}

if ($done) {
list($mywidth, $myheight, $garbage) = getimagesize("$pwd/$files[$f]");
$name = "javascript:location.href = 'pic.php?img=".addcslashes("$mypath$files[$f]", "\'\"")."';";
$thumb = "pic.php?img=$mypath$files[$f]&amp;thumb=1";

if (!$files[$f]) break;

$f++;
}

if ($name) {
$islink = is_link("$pwd/$filename");
$pathinfo = pathinfo($filename);
$pathinfo = $pathinfo[extension];
if (strlen($filename) - strlen($pathinfo) >= 15) {
$filename = substr($filename, 0, 11)."... .".$pathinfo;
}

if ($islink) $filename = "<span style=\"color: #ff6; font-style: italic\">$filename</span>";
echo "
<div class=\"imgholder\" title=\"$title\"
onmouseover=\"setcolor(this, '$hovercolor'); setcolor('title$x', '$hovertitle');\"
onmouseout=\"setcolor(this, '$normalcolor'); setcolor('title$x', '$normaltitle');\"
onmousedown=\"setcolor(this, '$activecolor'); setcolor('title$x', '$activetitle');\"
onclick=\"$name\">
<div style=\"display: table-row\">
<div class=\"imageframe\">
<!--[if IE]>
<table cellspacing=0 cellpadding=0><tr><td height=\"$maxheight\">
<![endif]-->
<img";
if ($done) {
echo " class=\"border\"";
} else {
echo " style=\"border: 0\"";
}
echo "
src=\"$thumb\"
title=\"$title\" alt=\"$title\"/>
<!--[if IE]>
</td></tr></table>
<![endif]-->
</div>
</div>
<div style=\"display: table-row\">
<div class=\"imgTitle\" id=\"title$x\">
$filename
</div>
</div>
</div>
";
}
}

include "$footername";
?>


and simple config for it:



<?
$masterpath = "/var/ftp/pub/pictures";
/* jail sript to this directory, do not allow parent */
$cache= "/var/cache/apache/galeria";
/* where to keep thumbnail images */
$maxwidth = $maxheight = 150;
/* size of thumbnails, you can also use $maxwidth = ($small) 40 : 150; for example */

$lang = "pl";
/*feature for language*/

/* header and footer name*/
$headername = "./myheader.php";
$footername = "./myfooter.php";
?>


Needs more customising, but out of the box, it should work just fine

http://ftp.id.uw.edu.pl/pub/pictures/ the thing in action.
http://ftp.id.uw.edu.pl/pub/texts/gallery.tgz the gallery in such form, packed and ready to use

ItsMeOnly
10-21-2006, 06:45 PM
My old faithful "image handler for galleries


<?php

/* what we can handle */
$imgtype = array(1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp', 'tiff',
'tiff', 'jpc', 'jp2', 'jpx', 'jb2', 'swc', 'iff', 'wbmp', 'xbm');

$img = stripslashes($_GET['img']);
$thumb = $_GET['thumb'];
$small = $_GET['small'];
/* we can generate two sorts of thumbs basically, big and small ones- like two step preview */

$sm = ($small) ? "sm_" : "";
/* append to thumbnail filename */

$type = $_GET['type'];
/* about this later, nifty xsl safeguard */

/* what we do for images with question mark in name? first strip it, then get it back! */
if (isset($img)) $img = str_replace("=63", "?", $img);
else die("No image set for displaying");

function updateThumb() {
global $imgtype, $mimetype, $img, $thumbnail,
$maxwidth, $maxheight, $width, $height;

if ($width > $maxwidth) {
$newwidth = $maxwidth;
(int) $newheight = ( $maxwidth / $width ) * $height;
} else {
$newwidth = $width;
$newheight = $height;
}

if ($newheight > $maxheight) {
$newheight = $maxheight;
(int) $newwidth = ( $maxheight / $height ) * $width;
};

$newimage = imagecreatetruecolor($newwidth, $newheight);

switch($mimetype) {
case 1:
$content = @imagecreatefromgif("$img");
break;
case 2:
$content = @imagecreatefromjpeg("$img");
break;
case 3:
$content = @imagecreatefrompng("$img");
break;
case 7:
case 8:
$content = @imagecreatefromtiff("$img");
break;
default:
/* change me!*/
$content = shell_exec("/usr/bin/convert $img png:-");
$content = imagecreatefromstring("$content");
break;
};

if ($content) {
imagecopyresampled( $newimage, $content, 0, 0, 0, 0,
$newwidth, $newheight, $width, $height );
imagedestroy($content);
};

imagejpeg($newimage, $thumbnail, 92);
imagedestroy($newimage);
}

/*edit me */
function doHTML($img, $base) {
include "messages.txt";
global $masterpath, $headername, $footername;

$tmpimg = "$masterpath/$img";
list($width, $height, $mimetype) = getimagesize("$tmpimg");
$exifdata = @exif_read_data("$tmpimg", "EXIF");

include "$headername";

echo "
<div id=\"imagearea\">
<img src=\"".$_SERVER['PHP_SELF']."?img=$img&amp;type=$base\"
style=\"margin: auto\" title=\"$img\" alt=\"$img - full size\"/>
</div>
<div class=\"data\" id=\"imageData\">";

/* if you have any information about image in accompanying text file...*/
if (file_exists("$masterpath/$img.txt")) {
$myText = file_get_contents("$masterpath/$img.txt");
$myText = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
"<a href=\"\\0\">\\0</a>", $myText);
$myText = nl2br($myText);
echo "<div class=\"normaltext\">$myText</div><hr />";
unset($myText);
}

echo "
<b class=\"label\" style=\"width: 100%\">$tmpimg</b><br />
$filesize: " . filesize($tmpimg) . " $bytes, $img_res $width"."x$height<br />";

echo "$Modified (GMT): " . date("Y:m:d G:i", filemtime($tmpimg));

/* exif time- replace "$img_" strings with plaintext, normally I'm using "localised" text */
if ($exifdata) {
if ($exifdata[ExposureTime]) {
$exposuretime = split("/", $exifdata[ExposureTime]);
if (($exposuretime[0] == 10) &&
($exposuretime[1] % 10 == 0)) {
$exposuretime = "1/" . ($exposuretime[1] / 10);
} else if ($exposuretime[0] % $exposuretime[1] == 0) {
$exposuretime = ($exposuretime[0] / $exposuretime[1]);
} else $exposuretime = $exifdata[ExposureTime];
}
echo "<br />
EXIF: $ctime: ";
echo ($exifdata[DateTime]) ? $exifdata[DateTime] : $exifdata[DateTimeOriginal];
echo "<br />
EXIF: $img_ores: $exifdata[ExifImageWidth]x$exifdata[ExifImageLength],
DPI: x=".(int) $exifdata[XResolution]." y=".(int) $exifdata[YResolution]."<br />
EXIF: $img_caminfo: $exifdata[Make] $exifdata[Model]<br />";

if (isset($exifdata[ExposureBiasValue])) {
$tmpnum = split("/", "$exifdata[ExposureBiasValue]");
$tmpevbias = $tmpnum[0] / $tmpnum[1];
}

if (!isset($shortexif)) {
echo "
EXIF: ";
if (isset($exifdata[ExposureProgram])) {
$tmpnum = $exifdata[ExposureProgram];
echo "$img_exposureprog: $img_exposureprogt[$tmpnum], ";
}

echo "$img_exposuretime: $exposuretime"."s,<br />";

if (isset($tmpevbias)) printf("EXIF: %s: %+.2f, ", $img_evbias, $tmpevbias);
echo "ISO $exifdata[ISOSpeedRatings];<br />";

if (isset($exifdata[Flash])) {
$tmpnum = $exifdata[Flash];
echo "
EXIF: $img_flasht[$tmpnum];<br />";
}

echo "
EXIF: $img_focallength: ". ($exifdata[FocalLength] / 10) . "mm,
$img_aperture: ". $exifdata[COMPUTED][ApertureFNumber] .",
$img_digitalzoom: ". ($exifdata[DigitalZoomRatio] / 100). "x;<br />";
} else {
echo "EXIF: ISO $exifdata[ISOSpeedRatings], ";
if (isset($tmpevbias)) printf("EV: %+.2f, ", $tmpevbias);
if ($exposuretime) echo "t=$exposuretime, ";
echo $exifdata[COMPUTED][ApertureFNumber] .", f=".
($exifdata[FocalLength] / 10) . "mm, D=".
($exifdata[DigitalZoomRatio] / 100). "x.";
}
}
echo "</div>";
include "$footername";
}


/* this is cross-site linking safeguard, also simple mean to use the same script for multiple galleries */
$query_string = explode("?", $_SERVER['HTTP_REFERER']);
$basename = basename($query_string[0],
stristr($query_string[0], ".htm"));
unset($query_string);

if (!isset($headername)) $headername = "header.inc";
if (!isset($footername)) $footername = "footer.inc";

if (!file_exists("$basename.conf")) {
if (!$type) {
include $headername;
echo "
<div style=\"text-align:left\">
<h2 class=\"bigtitle\">Configuration file for viewer is not present or<br />
configuration directive has not been specified.<p />
Cannot continue - bailing out.</h2>
Called from $basename (".stristr($_SERVER['HTTP_REFERER'], ".htm") ."
</div>";
include $footername;
exit();
} else {
include "$type.conf";
$myfile = "$type.conf";
}
} else {
include "$basename.conf";
$myfile = "$basename.conf";
}


$scaling_needed = false;
$update_needed = false;

if ($thumb) {
$tmpimg = $img;
$img = "$masterpath/$img";

$mysize = filesize("$img");
$thumbnail = "$cache/$sm$tmpimg-$mysize";

if (getimagesize("$img")) {
list($width, $height, $mimetype) = getimagesize("$img");

if (($width > $maxwidth) || ($height > $maxheight))
$scaling_needed = true;
} else {
header("HTTP/1.0 404 Not found");
die();
}

$dirpath = dirname($thumbnail);
if (!is_dir($dirpath)) mkdir($dirpath);

if ((!file_exists($thumbnail)) || (filemtime($img) > filemtime($thumbnail)) ||
(filemtime($_SERVER[SCRIPT_FILENAME]) > filemtime($thumbnail)) ||
(filemtime($myfile) > filemtime($thumbnail))) {
$update_needed = true;
}

if ($scaling_needed) {
if ($update_needed) updateThumb();
header("Content-type: image/jpeg");
header('Content-transfer-encoding: binary');
readfile($thumbnail);
} else {
if (getimagesize("$img")) {
header("Content-type: image/$imgtype[$mimetype]");
header('Content-transfer-encoding: binary');
header('Content-length: '.filesize($img));
readfile($img);
} else {
header("HTTP/1.0 404 Not found");
die();
}
}
} else {
if (!file_exists("$masterpath/$img")) {
$mypath = dirname("$img");
header("Location: http://rambo.id.uw.edu.pl/viewer.html?path=$mypath");
} else {

/* S A F E G U A R D ! ! ! */
if ($type) {
if ($_SERVER['HTTP_REFERER'] && !isset($_GET[wrap])) {
include "$type.conf";
$img = "$masterpath/$img";
if(@getimagesize("$img")) {
list($garbage, $garbage, $mimetype) = getimagesize("$img");

header("Content-type: image/$imgtype[$mimetype]");
header('Content-transfer-encoding: binary');
header('Content-length: '.filesize($img));
readfile($img);
} else {
header("HTTP/1.0 404 Not found");
die();
}
} else {
doHTML($img, $type);
}
} else {
if ($_SERVER['HTTP_REFERER']) {
doHTML($img, $basename);
}
}
}
};
?>

syntax: ?img=path/image&type=config&thumb=[0|1]&small=[0|1]

About the safeguard, and multipurpose use: normally picture/thumbviewer was guessing from refering URL what kind of config (look, size of thumbnails, cache, and path) it should use, you can remove the "basename" stuff (bright red stuff at the end) and replace it with include "gallery.conf", if you're not using alternate layouts, sizes, etc. Also, if you're just for the displaying images and generating thumbnails, you could simply replace the conditional statement "if ($type)" from the S A F E G U A R D stuff.

The dark red section is for the "wrapper", basically this thing calls itself recursively, first generating a web page, wrapping it in html, and displaying file information, and then calling itself again, this time generating real image.

the original name, as used with conjunction with gallery above is pic.php

djr33
10-27-2006, 10:12 AM
Ok. Updates:
1. getimagesize now used to check image type in both pages; more efficient structure.
2. md5_file and storing thumbnails now in place.

Notes/problems:
1. The directory "_thumbs" had to be created manually. What's the easy way to do this in PHP? (though, including it in the script does seem like one extra thing to run each time, if the creation need only be once, but... makes sense... why not.)
2. Due to the strange way that imagejpeg($image,$filename,$quality) works, when it creates an image and stores it as $filename, the output is a textual representation of the filename, not the image. However, if the middle (filename) value is left null (as it is when displaying if the image IS found), then the output is fine. This means one load without seeing the image, but the image loads from then on. This would be fine if the admin wanted to run the script each time a new image was added... not that big a hassle. But.... would be nice to fix. I could do an output buffer and avoid the error that way, then output the new image, but that seems a pain. Any ideas here? I could also just create the image differently, as a file, not using a GD function. But again, doesn't seem like it makes sense. There must be something wrong with this function.

Here's the code:
INDEX.PHP
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Image Browser</title>
<style type="text/css">
ul.dirlist, ul.dirlist li {
list-style-type: none;
}
a {
color: #0000FF;
}
div.border {
border-left-style: solid;
border-bottom-style: solid;
border-color: #000066;
border-width: thin;
}
</style>
</head>
<body bgcolor="#000000" text="#0000FF">
<?php
$page = substr($_SERVER['SCRIPT_NAME'],(strrpos($_SERVER['SCRIPT_NAME'],"/")+1));
function checkDir($c,$skipimages=0) {
echo('<div class="border"><ul class="dirlist">');
$d = opendir($c);
while($f = readdir($d)) {
if(strpos($f, '.') === 0) continue;
$ff = $c . '/' . $f;
if (@getimagesize($ff)) {
$imginfo = getimagesize($ff);
}
if ($imginfo[2] == 1 || $imginfo[2] == 2 || $imginfo[2] == 3) {
$imgtypeok = 1;
}
if ($imgtypeok == 1 && $skipimages != 3) {
if ($skipimages != 1) {
$fff = '<img src="thumbnail.php?image='.urlencode($ff).'" border="">';
echo('<a href="' . $ff . '">' . $fff . '</a>'."\n");
}
else {
$n++;
}
}
if(is_dir($ff) && substr($ff,(strlen($ff)-7)) != "_thumbs") {
$fflink = $ff;
if (substr($ff,0,2) == "./") $fflink = substr($ff,2);
echo '<li><a href="'.$page.'?'.urlencode($fflink).'"'."><b>$f</b></a></li>\n";
global $dir;
if ($ff == $dir) $skipimagesnext = 0;
else $skipimagesnext = 1;
if ($skipimages == 2) $skipimagesnext = 2;
if ($skipimages == 3) $skipimagesnext = 3;
checkDir($ff,$skipimagesnext);
}
}
if ($n != "") echo "($n images)\n";
echo('</ul></div>');
}

$uri = explode("?",$_SERVER['REQUEST_URI'],2);
$dir = urldecode($uri[1]);
if(is_dir($dir)) {
checkDir($dir);
if(strpos($dir,"/") !== FALSE) {
$updir = "?".substr($dir,0,strrpos($dir,"/"));
echo '<a href="'.$page.$updir.'">^up^</a><br>'."\n";
}
echo '<a href="'.$page.'">Top</a>'."\n";
}
else if($dir == "all") checkDir(".",2);
else if($dir == "none") checkDir(".",3);
else checkDir(".");
echo '<a href="'.$page.'?none">Collapse All</a>'."\n";
echo '<a href="'.$page.'?all">Expand All</a>'."\n";
?>
</body>
</html>thumbnail.php
<?php
// The file
if ($_GET['image'] == "") die('Image Not Specified');
$filename = urldecode($_GET['image']);
if (@getimagesize($filename)) {
$imginfo = getimagesize($filename);
}
if ($imginfo[2] != 1 && $imginfo[2] != 2 && $imginfo[2] != 3) {
die('Image Filetype Incorrect');
}
//echo md5_file($filename)."jpg;".$filename."\n";
if (@getimagesize("_thumbs/".md5_file($filename).".jpg") !== FALSE) {
// Content type
header('Content-type: image/jpeg');
// Output
$thumb = imagecreatefromjpeg("_thumbs/".md5_file($filename).".jpg");
imagejpeg($thumb, null, 50);
}
else {
// Set a maximum height and width
$width = 200;
$height = 200;
// Get new dimensions
list($width_orig, $height_orig) = array($imginfo[0],$imginfo[1]);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Make image
if ($imginfo[2] == 1) {
if (@imagecreatefromgif($filename)) $image = imagecreatefromgif($filename);
}
else if ($imginfo[2] == 2) {
if (@imagecreatefromjpeg($filename)) $image = imagecreatefromjpeg($filename);
}
else if ($imginfo[2] == 3) {
if (@imagecreatefrompng($filename)) $image = imagecreatefrompng($filename);
}
if (!isset($image)) die('Image Filetype Incorrect.');
// Resample
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Content type
header('Content-type: image/jpeg');
// Output
imagejpeg($thumb, "_thumbs/".md5_file($filename).".jpg", 50);
}

?>

ItsMeOnly
10-27-2006, 04:59 PM
1. The directory "_thumbs" had to be created manually.
mkdir();


2. Due to the strange way that imagejpeg($image,$filename,$quality) works, when it creates an image and stores it as $filename, the output is a textual representation of the filename, not the image. However, if the middle (filename) value is left null (as it is when displaying if the image IS found), then the output is fine.

That is no strange, the generated jpeg should be valid format FILE, by leaving "filename" empty, you ask imagejpeg to output to "stdout":), omitting the saving the stream to disk.

However I see you are going to regenerate the thumbs manually if file content changes? right?

djr33
10-28-2006, 04:37 AM
mkdir. Easy. Thanks.

Ah. Ok, so I can just output the image that was placed there, then? I thought that calling imagejpeg() twice would screw things up.

No need to update anything manually. md5_file takes the contents of the image and creates a thumbnail named [md5].jpg. That way, if two images are the same, they can use the same thumbnail (saving a small bit of space, perhaps), and will allow updates to occur.... if the image (even with the same name) is updated, the file_md5() result won't match any of the thumbnails, so it will be updated.

There are a couple problems still happening that I will look into. (I think it stopped skipping non-image files once I used getimagesize, though not sure why, and a couple other things.)

I should also give a BIG warning--- the host suspended my account due to overstressing the server with this. I was converting about 600 thumbnails from about 900mb of photos.
The host is back up (since it's through someone I know, not just a normal hosting service), but it's worth knowing... this can really stress the processor.
I don't know any figures/numbers on it.... but.... yeah.

ItsMeOnly
10-28-2006, 10:30 AM
Tell me about it- I once pulled 132 thumbnails to regenerate (just dragging my mouse over will trigger the regeneration)- so I pulled it out... well, a screen for you of machine load.

http://rambo.id.uw.edu.pl/pic.php,Jokes/Computers/load.jpg,viewer,1,0.jpg
Normally the graph rarely goes beyond 1,2 lines (under heavy load, like compiling, or playing games). Needless to say, the load of 63 successfully _halted_ the server for about 5 minutes.

djr33
10-28-2006, 11:56 PM
Hmm..... fun. :p

I wonder if there's a way around it or something.

I guess just rendering the thumbnails isn't that big a deal.... it's a one time thing, after all.

After that, shouldn't be much to just load the pre-rendered thumbnails.

ItsMeOnly
10-30-2006, 02:44 AM
Actually, there is: you can either use session-based "semaphores", or restrict http server to n instances per client (sane value is 5).

blm126
10-30-2006, 11:15 PM
Wow, there is a lot of ugly coding in there. I'm attaching two versions of the thumbnail script. One is a commented version of yours, the other is how I would write it.


<?php
// The file
if ($_GET['image'] == "") die('Image Not Specified');
//**Don't do this. You should be using empty
$filename = urldecode($_GET['image']);
//**AHHHH!!!! This can cause horrible problems, this is done automatically
if (@getimagesize($filename)) {
//** I think you meant file_exists
$imginfo = getimagesize($filename);
}
if ($imginfo[2] != 1 && $imginfo[2] != 2 && $imginfo[2] != 3) {
die('Image Filetype Incorrect');
//**exit should be used
}
//echo md5_file($filename)."jpg;".$filename."\n";
if (@getimagesize("_thumbs/".md5_file($filename).".jpg") !== FALSE) {
//**Don't abuse functions, file_exists should be used.
// Content type
header('Content-type: image/jpeg');
// Output
$thumb = imagecreatefromjpeg("_thumbs/".md5_file($filename).".jpg");
imagejpeg($thumb, null, 50);
}
else {
// Set a maximum height and width
$width = 200;
$height = 200;
// Get new dimensions
list($width_orig, $height_orig) = array($imginfo[0],$imginfo[1]);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Make image
if ($imginfo[2] == 1) {
if (@imagecreatefromgif($filename)) $image = imagecreatefromgif($filename);
//file_exists
}
else if ($imginfo[2] == 2) {
if (@imagecreatefromjpeg($filename)) $image = imagecreatefromjpeg($filename);
//file_exists
}
else if ($imginfo[2] == 3) {
if (@imagecreatefrompng($filename)) $image = imagecreatefrompng($filename);
//And file exists
}
if (!isset($image)) die('Image Filetype Incorrect.');
//Else
// Resample
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Content type
header('Content-type: image/jpeg');
// Output
imagejpeg($thumb, "_thumbs/".md5_file($filename).".jpg", 50);
}

?>



<?php
// The file
if (empty($_GET['image']) exit('Image Not Specified');
$filename = $_GET['image'];
//echo md5_file($filename)."jpg;".$filename."\n";
if (file_exits("_thumbs/".md5_file($filename).".jpg")) {
// Content type
header('Content-type: image/jpeg');
// Output
$thumb = imagecreatefromjpeg("_thumbs/".md5_file($filename).".jpg");
imagejpeg($thumb, null, 50);
}
else if(file_exists($filename)) {
$imginfo = getimagesize($filename);
// Set a maximum height and width
$width = 200;
$height = 200;
// Get new dimensions
list($width_orig, $height_orig) = array($imginfo[0],$imginfo[1]);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Make image
if ($imginfo[2] == 1) {
$image = imagecreatefromgif($filename);
}
else if ($imginfo[2] == 2) {
$image = imagecreatefromjpeg($filename);
}
else if ($imginfo[2] == 3) {
$image = imagecreatefrompng($filename);
}
else{
exit('Image Filetype Not Supported.')
}
// Resample
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Content type
header('Content-type: image/jpeg');
// Output
imagejpeg($thumb,'_thumbs/'.md5_file($filename).'.jpg', 50);
}
else{
exit('File does not exist');
}

?>

djr33
10-30-2006, 11:45 PM
Thanks for the input... however, here's my reasoning for using the code I did. Please correct me if I'm wrong.


<?php
// The file
if ($_GET['image'] == "") die('Image Not Specified');
//**Don't do this. You should be using empty
////What if the url was ".php?image="?
$filename = urldecode($_GET['image']);
//**AHHHH!!!! This can cause horrible problems, this is done automatically
////No. In the original script, I use urlencode(), so this is reversing it.
if (@getimagesize($filename)) {
//** I think you meant file_exists
////No. Anything is a file. However, this checks if an IMAGE exists.
$imginfo = getimagesize($filename);
}
if ($imginfo[2] != 1 && $imginfo[2] != 2 && $imginfo[2] != 3) {
die('Image Filetype Incorrect');
//**exit should be used
////Why's that? die() works fine;
////According to php.net: "Note: This language construct is equivalent to die()."
}
//echo md5_file($filename)."jpg;".$filename."\n";
if (@getimagesize("_thumbs/".md5_file($filename).".jpg") !== FALSE) {
//**Don't abuse functions, file_exists should be used.
////See above-- checking for IMAGES, not FILES
// Content type
header('Content-type: image/jpeg');
// Output
$thumb = imagecreatefromjpeg("_thumbs/".md5_file($filename).".jpg");
imagejpeg($thumb, null, 50);
}
else {
// Set a maximum height and width
$width = 200;
$height = 200;
// Get new dimensions
list($width_orig, $height_orig) = array($imginfo[0],$imginfo[1]);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Make image
if ($imginfo[2] == 1) {
if (@imagecreatefromgif($filename)) $image = imagecreatefromgif($filename);
//file_exists
}
else if ($imginfo[2] == 2) {
if (@imagecreatefromjpeg($filename)) $image = imagecreatefromjpeg($filename);
//file_exists
}
else if ($imginfo[2] == 3) {
if (@imagecreatefrompng($filename)) $image = imagecreatefrompng($filename);
//And file exists
}
if (!isset($image)) die('Image Filetype Incorrect.');
//Else
// Resample
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Content type
header('Content-type: image/jpeg');
// Output
imagejpeg($thumb, "_thumbs/".md5_file($filename).".jpg", 50);
}

?>Again, thanks for the input. Please let me know, once reading why I did that.

blm126
10-31-2006, 12:59 AM
<?php
// The file
if ($_GET['image'] == "") die('Image Not Specified');
//**Don't do this. You should be using empty
////What if the url was ".php?image="?
//**read the manual entry on empty. It first checks if the variable is set, then it checks to make sure that it is not empty
$filename = urldecode($_GET['image']);
//**AHHHH!!!! This can cause horrible problems, this is done automatically
////No. In the original script, I use urlencode(), so this is reversing it.
//**PHP automatically calls urldecode on get variables. It ASSUMES they have been encoded already.Calling it twice can have weird results
if (@getimagesize($filename)) {
//** I think you meant file_exists
////No. Anything is a file. However, this checks if an IMAGE exists.
//**One thing at a time, You check if it is an image later on
$imginfo = getimagesize($filename);
}
if ($imginfo[2] != 1 && $imginfo[2] != 2 && $imginfo[2] != 3) {
die('Image Filetype Incorrect');
//**exit should be used
////Why's that? die() works fine;
////According to php.net: "Note: This language construct is equivalent to die()."
//** yes, it is equivalent(I try not to argue with the manual :) ), bu check out http://www.php.net/manual/en/aliases.php You will see that die is an alias, and also that they don't encourage the use of aliases.
}
//echo md5_file($filename)."jpg;".$filename."\n";
if (@getimagesize("_thumbs/".md5_file($filename).".jpg") !== FALSE) {
//**Don't abuse functions, file_exists should be used.
////See above-- checking for IMAGES, not FILES
//**See above, really checking for a file
// Content type
header('Content-type: image/jpeg');
// Output
$thumb = imagecreatefromjpeg("_thumbs/".md5_file($filename).".jpg");
imagejpeg($thumb, null, 50);
}
else {
// Set a maximum height and width
$width = 200;
$height = 200;
// Get new dimensions
list($width_orig, $height_orig) = array($imginfo[0],$imginfo[1]);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Make image
if ($imginfo[2] == 1) {
if (@imagecreatefromgif($filename)) $image = imagecreatefromgif($filename);
//file_exists
}
else if ($imginfo[2] == 2) {
if (@imagecreatefromjpeg($filename)) $image = imagecreatefromjpeg($filename);
//file_exists
}
else if ($imginfo[2] == 3) {
if (@imagecreatefrompng($filename)) $image = imagecreatefrompng($filename);
//And file exists
}
if (!isset($image)) die('Image Filetype Incorrect.');
//Else
// Resample
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Content type
header('Content-type: image/jpeg');
// Output
imagejpeg($thumb, "_thumbs/".md5_file($filename).".jpg", 50);
}

?>

As always I intend this to be nothing but constructive critism, so please don't take offense.

djr33
10-31-2006, 02:49 AM
No, no offense taken. I really didn't understand the reasoning for some of that.
Ok, empty is fine... any reason not to do it like I did?
die()-- i've seen this and been using it from example. Either way....
ok, I thought that the urldecode was important for that since I did it manually in the original script.

Now.... the one thing I really don't agree with....
"//**One thing at a time, You check if it is an image later on "
What possible reason would I not use a function that checks both if it's an image and if it exists? I don't see the logic here.
In other circumstances, that would make sense, but any non-images aren't supposed to return true either, so seems like it just saves a step, and after that point, there's no need to escape the errors with @getimagesize() later.

blm126
10-31-2006, 03:24 AM
In my mind file_exists should be better for performance. Why should you force PHP to get all that information for you when you are only interested in whether the file exists?

Now, about empty. The way you did it could cause PHP to throw a warning. Look at the following


if(isset($_GET['somevar'] && $_GET['somevar'] != ''))



if(!empty($_GET['somevar']))

Those two are the same. I tend to use empty as it is shorter.However, the following is not the same


if($_GET['somevar'] != '')

If $_GET['somevar'] does not exist PHP will throw a warning. You normally don't catch mistakes like this because many servers are set up to not display warnings.

Another small performace thing I noticed in your code is your use of quotes. Supposedly, a single quote( ' ) is faster for PHP to parse than a double quote ( " )

All of these things(except for the urldecode problem) are mostly small habits that will make your code more efficient. At least, I hope they will because that is the only reason I do them.

djr33
10-31-2006, 03:33 AM
"In my mind file_exists should be better for performance. Why should you force PHP to get all that information for you when you are only interested in whether the file exists?"
Because I will be using that funtion later, and if it returns false, which it likely will if there are other files around, then it will save the processor from checking BOTH if it exists as a file then later as an image.

I'll agree that using double quotes is a habit, but it's nice when you want something inside to be parsed, like a variable, \n, etc.

blm126
10-31-2006, 10:16 PM
The only way to really tell which is better will be to time it.

Twey
10-31-2006, 10:45 PM
Supposedly, a single quote( ' ) is faster for PHP to parse than a double quote ( " )The key word I used is "marginally" :) It's a good idea to use single quotes where possible, but if someone forgets, it's not exactly a big deal. They add perhaps twenty milliseconds onto their code execution time.

djr33
11-01-2006, 12:34 AM
Also, I think that:
"stuff\n";
would be faster than:
'stuff'."\n";

(Though yes, 'stuff' is faster than "stuff")

Twey
11-01-2006, 05:43 PM
<?php
function avg($arr) {
$total = 0;
for($i = 0; $i < count($arr); ++$i)
$total += $arr[$i];
return $total / count($arr);
}

$times1 = array();
$times2 = array();
for($i = 0; $i < 10000; ++$i) {
$s = microtime();
'Hello' . "\n";
array_push($times1, microtime() - $s);
$s = microtime();
"Hello\n";
array_push($times2, microtime() - $s);
}

echo 'Average for single/double concatenation: ' . avg($times1) . "\n" .
'Average for only double: ' . avg($times2) . "\n";
?>Output:
Average for single/double concatenation: 1.7569E-06
Average for only double: 1.6627E-06It is.