I recently had a need to provide a PHP-scripted "photo album" functionality for a customer's web site.
Nothing I found on the web seemed to work under PHP 4.2-5.0, so I wrote my own. It is fairly simple to read a directory, find certain files by extension, and sort the list alphabetically. In fact, on a UNIX/Linux server, alphabetical sorting is the default return of the readdir() function:
Snippet 1:
$dh = opendir($dir);
while ($file = readdir($dh))
{
$files[] = $file;
}
closedir($dh);
In the snippet above, filenames (all of them) are read one at a time into a single-level array, "$files[]". My implementation of a photo-album metaphor requires all files (including subdirectories) in the target directory be listed in the array. I treat the various file types differently as I fetch the actual files in order that they appear in the $files[] array. If all you want is, for example, all the ".jpg" files or some such other discrimination, you should add code to the "while" loop above the array assignment line:
Snippet 2:
$dh = opendir($dir);
while ($file = readdir($dh))
{
if($getFileExtension($file) == ".jpg")
$files[] = $file;
}
closedir($dh);
function getFileExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = strtolower(substr($str,$i+l,$l));
return $ext;
}
When I generalized the script for publication I began another web search for ways to sort by other criteria, such as the file's upload (creation) date. Interestingly, one person's contribution of a lengthy approach seemed to appear on many pages returned in a Google search. I found that this code block also didn't work on PHP 4.2-5.0 for some reason, and again had to come up with an original scheme.
It turns out sorting by creation date is not at all difficult nor does it require many lines. I did it in three steps: First, perform the directory read, then retrieve the file's "modified" date, and save that in an intermediate array keyed to the filename:
Snippet 3:
$dh = opendir($dir);
while ($file = readdir($dh))
{
$fName = "$dir/$file";
$fTime = filemtime($fName);
$files_array[$file] = $fTime;
}
closedir($dh);
Then sort the intermediate associative array using "asort()" to retain the correlation of filename index with the date:
Snippet 4: asort($files_array);
The rest of my script references the original single-level array "$files[]", so in this third step I read the filenames in sorted order into my working array for the remainder of the script:
Snippet 5:
foreach ($files_array as $file => $date)
{
$files[] = $file;
}
My "$files[]" array now holds a simple list of the directory's files in order of increasing date (i.e., oldest first). To reverse the order, putting the newest first, simply change the function used in Snippet 3 to the "arsort()" function.
Copyright 2007 Richard Nilsson. Verbatim copying and redistribution of this entire article are permitted without royalty in any medium provided this notice is preserved.