How get first modified file in a folder using PHP?

297 views Asked by At

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?

1

There are 1 answers

0
COLD TOLD On BEST ANSWER

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);
    ?>