PHP-如何从目录AND子目录中获取最新的文件


PHP - how to get most recent file from directory AND subdirectories

我已使用以下脚本正确显示所选目录及其子目录中的所有文件。有人知道如何修改此代码吗?只在目录/子目录中回显最新的文件?

函数ListFiles($dir){if($dh=opendir($dir)){$files=Array();$inner_files=Array();while($file=readdir($dh)){if($file!="."&&$file!".."&&$file[0]!='.'){if(is_dir($dir."/".$文件)){$inner_files=ListFiles($dir."/".$file);if(is_array($inner_files))$files=array_merge($files,$inner_files);}其他{array_push($files,$dir."/".$file);}}}closedir($dh);返回$files;}}foreach(将文件('media/com_form2content/documents/c30')列为$key=>$file){echo"{aridoc-engine=''"google''"width=''"750''"height=''"900''"}"$文件"{/aridoc}";}

PHP5中,可以使用RecursiveDirectoryIterator递归扫描目录中的所有文件:

$mostRecentFilePath = "";
$mostRecentFileMTime = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("YOURDIR"), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        if ($fileinfo->getMTime() > $mostRecentFileMTime) {
            $mostRecentFileMTime = $fileinfo->getMTime();
            $mostRecentFilePath = $fileinfo->getPathname();
        }
    }
}

您可以使用filemtime()来检索文件上次修改的unix时间戳。

您可以使用它来获取目录中的最后一个添加文件

$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;
    }
  }
}

你可以试试这个

$last_mtimes = array(); 
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
    if($file != "." && $file != ".." && $file[0] != '.') {
        if(is_dir($dir . "/" . $file)) {
            $inner_files = ListFiles($dir . "/" . $file);
            if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
        } else {
            array_push($files, $dir . "/" . $file);
             $lmtime = filemtime($dir . "/" . $file) ;
             $last_mtimes[$lmtime] = $dir . "/" . $file;
        }
    }
}
 // now ksort your $last_mtimes array
krsort($last_mtimes);
// either return this array or do whatever with the first val
closedir($dh);
return ($last_mtimes);
}
}
// prints in decsending order
foreach (ListFiles('PATH_TO_YOUR_DIRECTORY') as $key=>$file){
echo "{aridoc engine='"google'" width='"750'" height='"900'"}" . $key."=>".$file ."  {/aridoc}";
 }
 // prints last modified files
 echo array_shift(ListFiles('YOUR_DIRECTORY_PATH'));

希望这对有帮助

我建议您使用filemtime()函数。

这将为您提供上次修改文件的日期。