hillz hillz - 8 months ago 27
PHP Question

How to sort files based on the last upload time?

I have some files in my website and I want to display them, here's my script:


// open this directory
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory)) {$dirArray[] = $entryName;} closedir($myDirectory);
$indexCount = count($dirArray);
echo "$indexCount files<br/>";

echo "<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks><TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th><th>Upload Date</th></TR>\n";

for($index=0; $index < $indexCount; $index++)
if (substr("$dirArray[$index]", 0, 1) != ".")
echo "<TR>
<td><a href=\"http://didieksuriadi.ml/bullshit/$dirArray[$index]\">$dirArray[$index]</a></td>
<td>".date("H:i:s # d-F-Y.",filemtime($dirArray[$index]))."</td>
echo "</TABLE>";
echo date("h:i:sa");

The problem is that, that script doesn't list all my files based on the upload time, what I want is that the most recent uploaded file should show up first so that I wouldn't have to scroll down to see the newest file. The demo can be seen at http://didieksuriadi.ml/bullshit/


Well, you sorted it but not by filemtime(). Also, that's a lot of code:

array_multisort($times = array_map('filemtime', $files = glob("*")), SORT_DESC, $files);

foreach($files as $key => $file) {
    // echo HTML and stuff
    echo "{$file}<br>";
    echo "{$times[$key]}<br>";
  • Use glob() to get all files in an array $files
  • Pass filemtime to array_map() to get an array of $times for each file
  • Sort $files array by $times array using array_multsort()
  • Loop through the $files and use $file and $times[$key] for the file's time