Search code examples
phpreaddir

php read directory sorting


i have a little php script that reads a directory and then echos all the files (jpg's in this case) into a jquery image slider. it works perfectly, but i dont know how to sort the images by name desending. at the moment the images are random.

<?php
$dir = 'images/demo/';
if ($handle = opendir($dir)) {

while (false !== ($file = readdir($handle))) {
    echo '<img src="'.$dir.$file.'"/>';
}

closedir($handle);
}
?>

any help on this would be great.

one more thing i dont understand. the script pics up 2 nameless non jpg files in that folder that does not exist??? but i havnt realy checked into that yet


Solution

  • Try this:

    $dir = 'images/demo/';
    $files = scandir($dir);
    rsort($files);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            echo '<img src="' . $dir . $file . '"/>';
        }
    }