开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜