phpsortingopendir

PHP readdir() not returning files in order


I have the below code that I run to list files within a directory. I would like to sort the output by some way. Preferably filename or by date of upload. Is this even possible?

<?php
  if ($handle = opendir('./xyz')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
          $thelist .= '<a href="./abc/xyz/'.$file.'">'.$file.'</a><br>';
        }
    }
  closedir($handle);
  }
?>
<h1>List of files:</h1>
<ul><?php echo $thelist; ?></ul>

EDIT: New code with update.

<?php
array_multisort(array_map('filectime', $files = glob('./xyz/*.*')), SORT_DEC, $files);
?>

<h1>List of files:</h1>
<ul><?php foreach($files as $file) {
    echo '<a href="./abc/'.$file.'">'.$file.'</a><br>';
}
?></ul>

Solution

  • You can't sort with readdir which reads them in the order that they are stored in the file system. You can read them into an array and sort that. array_multisort works well and you can replace filectime with other functions:

    array_multisort(array_map('filectime', $files = glob('./xyz/*.*')),
                    SORT_ASC, $files);
    

    Once you have the sorted array just loop it and display or build your string as you were:

    foreach($files as $file) {
        echo '<a href="./abc/xyz/'.$file.'">'.basename($file).'</a><br>';
    }