php 获取目录中最后修改的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5448374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get last modified file in a directory
提问by dynamic
Is there a way to select only the last file in a directory (with the extensions jpg|png|gif
?)
有没有办法只选择目录中的最后一个文件(带有扩展名jpg|png|gif
?)
Or do I have to parse the entire directory and check using filemtime
?
或者我必须解析整个目录并检查使用filemtime
?
回答by mario
Yes you have to read through them all. But since directory accesses are cached, you shouldn't really worry about it.
是的,你必须通读它们。但是由于目录访问被缓存,所以您不必担心。
$files = array_merge(glob("img/*.png"), glob("img/*.jpg"));
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);
$latest_file = key($files);
回答by Pascal MARTIN
I don't remember having ever seen a function that would do what you ask.
我不记得曾经见过可以执行您要求的功能。
So, I think you will have to go through all (at least jpg/png/gif)files, and search for the last modification date of each of them.
因此,我认为您必须浏览所有(至少是 jpg/png/gif)文件,并搜索每个文件的最后修改日期。
Here's a possible solution, based on the DirectoryIterator
class of the SPL :
这是一个可能的解决方案,基于DirectoryIterator
SPL的类:
$path = null;
$timestamp = null;
$dirname = dirname(__FILE__);
$dir = new DirectoryIterator($dirname);
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
if ($fileinfo->getMTime() > $timestamp) {
// current file has been modified more recently
// than any other file we've checked until now
$path = $fileinfo->getFilename();
$timestamp = $fileinfo->getMTime();
}
}
}
var_dump($path);
Of course, you could also do the same thing with readdir()
and other corresponding functions.
当然,你也可以用readdir()
和 其他相应的函数来做同样的事情。
回答by Waqar Alamgir
function listdirfile_by_date($path)
{
$dir = opendir($path);
$list = array();
while($file = readdir($dir))
{
if($file != '..' && $file != '.')
{
$mtime = filemtime($path . $file) . ',' . $file;
$list[$mtime] = $file;
}
}
closedir($dir);
krsort($list);
foreach($list as $key => $value)
{
return $list[$key];
}
return '';
}
回答by Shamsher Sidhu
Use this code:
使用此代码:
<?php
// outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>