Skip to content
Advertisement

How to sort files by date in PHP

I currently have a script which allows me to output the list of files inside the same directory.

The output shows the names, and then I used filemtime() function to show the date when the file was modified.

How will I sort the output to show the latest modified file?

This is what I have for now:

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $lastModified = date('F d Y, H:i:s', filemtime($file));
            if(strlen($file)-strpos($file, ".swf") == 4) {
                echo "$file - $lastModified";
            }
        }
    }
    closedir($handle);
}

Advertisement

Answer

You need to put the files into an array in order to sort and find the last modified file.

$files = array();
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
           $files[filemtime($file)] = $file;
        }
    }
    closedir($handle);

    // sort
    ksort($files);
    // find the last modification
    $reallyLastModified = end($files);

    foreach($files as $file) {
        $lastModified = date('F d Y, H:i:s',filemtime($file));
        if(strlen($file)-strpos($file,".swf")== 4){
           if ($file == $reallyLastModified) {
             // do stuff for the real last modified file
           }
           echo "<tr><td><input type="checkbox" name="box[]"></td><td><a href="$file" target="_blank">$file</a></td><td>$lastModified</td></tr>";
        }
    }
}

Not tested, but that’s how to do it.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement