PHP: Directory Listing: ImagesFollowing 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 DirectoryWe 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 OutputThe 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";
}
?>
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 bugSome 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
Send Feedback |
|
|
© Copyright 2012 Chirp Internet
- Page Last Modified: 23 September 2011
|
|
User Comments and Notes
Skyler Call 5 January, 2010
Is there a way to have the images displayed in numerical/alphabetical order?
Jonathan Broome 17 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
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.
Sabrina 3 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)
Stephan 27 December, 2010
Thanks for pointing out the mime magic bug - that was what i was faced with and now managed to solve.
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
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.
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!