Create A Quick Image Directory In PHP On Your Webserver

Last Edited: 2014-06-15 22:39:57


Ever have a bunch of images in various image directories around your webserver whilst looking for one of them. I sure have. But going through webservers isn't the funnest way to spend your Saturday night. Looking through your own computer is easy because windows and mac both have applications that will show thumbnails of all of the images. Webservers are sometimes not so friendly, especially if they are remote servers. How can I view images in a folder? Funny you should ask, because Ima bout to tell you.


I wrote this script years ago and adjusted it along the way. It is very simple PHP so you could use it as a quick tutorial into the world of PHP if you want. All you need to do is find a directory of images on your server that is accessible via the web. Make a new file in your directory that contains your images.. I normally have named it "dir.php". You can also name it "index.php" so that if you go directly to that folder name in a web browser - the script will be run automatically.




<?php

$i=0;

$dir = ".";

$handle = opendir($dir);

while($file = readdir($handle)){

if($file != "." && $file != ".."){

$is = getimagesize($file);



?>

<td><center>

<a href="<?=$file; ?>" target="_blank">

<img src="<?=$file; ?>" <?php if($is[0]>200){ ?> width="200"<?php } ?>
border="0">

</a><Br>

<?=$file; ?> <?=$is[0]."x".$is[1]; ?></center></td>

<?php if($i==4){

$i=0; ?>

</tr><tr>

<?php } else {

$i++;

}

}

}

?>

This code starts a counter with $i - you will use that to make new rows as you display images. Then the current directory in programming can be accessed with ".". Use opendir to open up the handle, or the pointer that scans through the directory. (Sidenote: this can also be handled with scandir, but I still have a hard time remembering that when I program a loop through a directory) Use getimagesize() to find the width and height of the image. As you're looping through, you are making an HTML table with each <td> containing the image, which is a link to the image and the image size.


That's it! Depending on the physical size of your images, you may want more in a row, just change the $i==4 to $i==# you want to display. Be warned that if you drop this into a directory that has just a ton of images, especially huge images, you may crash your browser and have to restart it. There's only so much infood (info + food) you can feed a browser before it just refuses to eat any more. So keep that in mind.


Comments

Categories

Recent Posts