我需要从该目录下以名称file_(随机数).css开始的文件数量中获得最新更新的文件?有一些文件像这样存在:
file_12.css
file_34.css
file_14.css
我想获得最近更新的文件。PHP中是否有现成的函数来检索这样的文件?
有:
int filemtime ( string $filename )
信息:http://php.net/manual/en/function.filemtime.php
string readdir ([ resource $dir_handle ] )
信息:http://php.net/manual/en/function.readdir.php
或
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
信息:http://www.php.net/manual/en/function.scandir.php
我认为您可以使用filemtime
和readdir
的组合将所有文件名和最后更新时间读入数组(以修改时间作为键,以文件名作为值),使用排序函数,然后获取修改时间最大的文件。
类似下面的代码应该可以达到这个效果(未测试):
<?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);