简体   繁体   中英

Get the most recently updated file in PHP

I need to get the latest updated file from number of files present under that directory starting with name file_(random number).css? there are number of file present like this:

file_12.css
file_34.css
file_14.css

I want to get the most recently updated file. is there any readymade function available to retrieve such file in PHP?

Yes there is:

int filemtime ( string $filename )

Info: http://php.net/manual/en/function.filemtime.php

string readdir ([ resource $dir_handle ] )

Info: http://php.net/manual/en/function.readdir.php

or

array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )

Info: http://www.php.net/manual/en/function.scandir.php

I suppose you could use a combination of filemtime and readdir to read all of the file's names and last updated time into an array (with the modified time as the key and the filename as the value), use a sorting function, and then grab the file with the greatest modified time.

Something like the following should do the trick (not tested):

<?php

$files = array();

if ($handle = opendir('/path/to/files')) {
    while (false !== ($file = readdir($handle))) {
        if (is_file($file)) {
            $modified = filemtime($file);
            $files[$modified] = $file;
        }
    }
    closedir($handle);
}

krsort($files);

$last_modified_file = array_shift($files);
function cmp($a, $b)
{
if(!is_file($b) || !strpos('file_', $b)) return -1;
$a = filemtime($a); 
$b = filemtime($b);   
return  ($a == $b) ? 0 :( ($a > $b) ? -1 : 1 );
}
usort($handle = scandir('/path/to/files'), "cmp");
$file = $handle[0];
unset($handle);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM