skip to content

PHP: Directory Listing: Images

Following on from the article on Directory Listing, here's another simple PHP script to display the contents of a directory of images within an HTML page.

Extracting Images from a Directory

We first define the file types that we want to be recognised and displayed. There's no reason why this couldn't be done within the function itself (below) but having it separate makes it easier to update.

<?PHP // filetypes to display $imagetypes = array("image/jpeg", "image/gif"); ?>

Then comes the main function. It takes a directory as an argument and returns a list of files who's type matches the array. Also returned is the size of the image as calculated by getimagesize. The function expects the variable passed to be the component of the path following the first /. For example "images" or "images/" would indicate the images directory at the root of the site.

Note: It's always easier in PHP to work with absolute paths (starting from /) - especially if you're using mod_rewrite which can confuse relative file paths.

<?PHP // Original PHP code by Chirp Internet: www.chirp.com.au // Please acknowledge use of this code by including this header. function getImages($dir) { global $imagetypes; // array to hold return value $retval = array(); // add trailing slash if missing if(substr($dir, -1) != "/") $dir .= "/"; // full server path to directory $fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir"; $d = @dir($fulldir) or die("getImages: Failed opening directory $dir for reading"); while(false !== ($entry = $d->read())) { // skip hidden files if($entry[0] == ".") continue; // check for image files $f = escapeshellarg("$fulldir$entry"); $mimetype = trim(`file -bi $f`); foreach($imagetypes as $valid_type) { if(preg_match("@^{$valid_type}@", $mimetype)) { $retval[] = array( 'file' => "/$dir$entry", 'size' => getimagesize("$fulldir$entry") ); break; } } } $d->close(); return $retval; } ?>

Formatting the Output

The function is called, and the result output to HTML, as follows:

<?PHP // fetch image details $images = getImages("images"); // display on page foreach($images as $img) { echo "<img class=\"photo\" src=\"{$img['file']}\" {$img['size'][3]} alt=\"\">\n"; } ?>

This HTML output can be easily formatted using CSS. Something like the following should give a decent effect:

<style type="text/css"> .photo { float: left; margin: 0.5em; border: 1px solid #ccc; padding: 1em; font-size: 10px; } </style>

As demonstrated here:


Or we can modify the output to also display the image filename and pixel dimensions:

<?PHP // fetch image details $images = getImages("images"); // display on page foreach($images as $img) { echo "<div class=\"photo\">"; echo "<img src=\"{$img['file']}\" {$img['size'][3]} alt=\"\"><br>\n"; // display image file name as link echo "<a href=\"{$img['file']}\">",basename($img['file']),"</a><br>\n"; // display image dimenstions echo "({$img['size'][0]} x {$img['size'][1]} pixels)<br>\n"; // display mime_type echo $img['size']['mime']; echo "</div>\n"; } ?>

2390736357.jpg
(100 x 67 pixels)
image/jpeg

2390735019.jpg
(100 x 67 pixels)
image/jpeg

2390370487.jpg
(79 x 80 pixels)
image/jpeg

2390737530.jpg
(100 x 67 pixels)
image/jpeg

2397734534.jpg
(100 x 56 pixels)
image/jpeg

If the images you want to display are very large, then you might want to look at using thumbnails that then link to the larger image. This is a more complicated process and beyond the scope of this article.

mime_magic bug

Some versions of PHP5 appear to have a bug relating to the mime_magic file and will return text/plain for all files. The work-around for UNIX-based systems is the following:

<?PHP // check for image files $f = escapeshellarg("$fulldir$entry"); if(in_array($mimetype = trim( `file -bi $f` ), $imagetypes)) { $retval[] = array( "file" => "/$dir$entry", "size" => getimagesize("$fulldir$entry") ); } ?>

Affected Windows users will have to rely on the file extension rather than the mime type.

Related Artices

< PHP


Send Feedback

Use this form to send a message to The Art of Web:


used only for us to reply, and to display your gravatar.

CAPTCHA refresh

<- copy the digits from the image into this box

press Esc or click outside this box to close

Load Feedback Form

User Comments and Notes

brigante 1 May, 2014

well oki, but try this way:

echo "<div class=\"photo\">";
echo "<a href=\"{$img['file']}\" target=\"_blank\"><img width=\"100\" height=\"100\" src=\"{$img['file']}\" {$img['size'][3]} alt=\"\" title=",basename($img['file'])," </a><br />";

is better do it so with width and height, because without these attributes is not cool
all images on the gallery must have got any sizes by this simple way all pics will have it

George Spelvman 17 October, 2013

This is the most complete code to list images in a given folder. Thanks so much!

Arty 20 March, 2012

Awesome script.
Just what the Doc ordered.
Worked first time.
Thank you so much

Phil 23 September, 2011

Thanks for the great little script.

Like @Paul, I am using it to display images which are want to be ordered alphabetically. To accomplish that, simply use the Sort function on your array before returning it. i.e.:

sort($retval);
return $retval;

Works great for me, and also yes thank you for the mime_magic bug, immediately upon having that problem there was the solution!

Paul 3 February, 2011

This is a great little script! I have one little problem though.

I'm using it to display a set of images in a directory that are numbered sequentially (i.e. 01.jpg, 02.jpg, 03.jpg...) yet they are being returned in a random order. Do have any suggestions on how to control this?

The order in which directory entries are returned by the read method is system-dependent. You can use the PHP sort function to order the output alphabetically, or check out sorting associative arrays.

turbocrab 25 January, 2011

This script has been an enormous help to me I have been able to manipulate my objects easily.
If it wasn't for people like you the web would never move forward. Thankyou

Stephan 27 December, 2010

Thanks for pointing out the mime magic bug - that was what i was faced with and now managed to solve.

Sabrina 4 November, 2010

Hello,

Where do i put al the text? for example, where do i put the text from 1. Extracting Images from a Directory

is that in the head? or what?

thnx

It doesn't matter where you place the PHP code from section 1 as long as it's written or included before you call the function (section 2)

Mark 9 October, 2010

Thanks for the little chunks of code but it would be very helpful if at the end you could have it all put together and complete so we can simply copy and paste it.

Thanks again.

Jonathan Broome 18 September, 2010

This might seem like a stupid question but what exactly do I enter as the parameter for the function? And also, where does all of this go (examples). Otherwise, excellent tutorial

Not a stupid questions. You can probably find the answer in this related article: PHP: Directory Listing

Skyler Call 6 January, 2010

Is there a way to have the images displayed in numerical/alphabetical order?

top