phpfiledirdatemodified

How get first modified file in a folder using PHP?


How get first modified file?

So far I've had:

$dir = $path.'/';
$firstMod = '';

$p = 1;
foreach (scandir($dir) as $file) {
if (is_file($dir.$file) && ... ) {


if($p == 1) break;
}
}

If I would like to get last file but not last modified but last in an folder order what should I use?


Solution

  • you can try to write all the files in the array make key as the date modified than reorder the array based on date and get the first element of array which would first modified.

    <?php
        $folder = "files/";
        $handle = opendir($folder);
        $files=array();
        while ($file = readdir($handle)){   
            if( $file != ".." && $file != "." ){
                $key = filemtime($file);
                $files[$key] = $file ;
            }
        }
        closedir($handle);
    
        ksort($files) ;
    
        echo reset($files);
        ?>