The simplest way would be to load all the filenames into an array and then sort them. Try this example:
Code: Select all
<?php
$path = "./portraits";
$image_array = array();
$dir_handle = @opendir($path) or die("Unable to open folder");
while (false !== ($file = readdir($dir_handle))) {
if(ereg("(.*)\.(jpg|JPG|bmp|jpeg|png|gif)", $file)) {
$image_array[] = $file;
}
}
closedir($dir_handle);
sort($image_array);
foreach ($image_array as $key => $value) {
echo "<img src='portraits/$value' height='100%'> ";
}
?>
Although the code isn't overly complex, things like arrays can catch you out. If you're new to PHP I would suggest taking a look at the main PHP site to see how the functions work, in this case for sort():
http://uk2.php.net/manual/en/function.sort.php
and then heading over to w3schools for some quick examples of how arrays work:
http://www.w3schools.com/php/php_arrays.asp
Also, if you're testing for file extensions it's a good idea to lowercase the whole filename for the purposes of your test. As an example, your script will test for image.jpeg but not IMAGE.JPEG as you would probably want it to do. You should also validate the filenames in case someone has created a filename with funny characters (either accidentally or for malicious reasons.) Another vulnerability is where people do something 'cute' like putting JavaScript code in a filename (an example of cross-site scripting) which is particularly dangerous if you're letting people upload their own files. The moral of that story - getting your script working is only half the battle, you then need to think about whether it's secure or not...once you start getting a conscience about doing stuff securely there's no way back - you have been warned!
HTH,
Mecha Godzilla