获取目录中最新添加的文件

php
2022-08-30 13:22:42

如何获取最新的文件名或添加到目录中的文件路径?


答案 1
$path = "/path/to/my/dir"; 

$latest_ctime = 0;
$latest_filename = '';    

$d = dir($path);
while (false !== ($entry = $d->read())) {
  $filepath = "{$path}/{$entry}";
  // could do also other checks than just checking whether the entry is a file
  if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
    $latest_ctime = filectime($filepath);
    $latest_filename = $entry;
  }
}

// now $latest_filename contains the filename of the file that changed last

答案 2
$dir = dirname(__FILE__).DIRECTORY_SEPARATOR;
$lastMod = 0;
$lastModFile = '';
foreach (scandir($dir) as $entry) {
    if (is_file($dir.$entry) && filectime($dir.$entry) > $lastMod) {
        $lastMod = filectime($dir.$entry);
        $lastModFile = $entry;
    }
}

推荐