在目录中添加最新文件

时间:2009-09-29 07:08:33

标签: php

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

8 个答案:

答案 0 :(得分:56)

$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

答案 1 :(得分:6)

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

答案 2 :(得分:5)

filectime适用于更改chmod值等元数据的时间。 filemtime用于实际内容更改。

答案 3 :(得分:3)

$dir = "/path/to/Your/dir";         
$pattern = '\.(zip|ZIP|pdf|PDF)$'; // check only file with these ext.          
$newstamp = 0;            
$newname = "";

if ($handle = opendir($dir)) {               
       while (false !== ($fname = readdir($handle)))  {            
         // Eliminate current directory, parent directory            
         if (ereg('^\.{1,2}$',$fname)) continue;            
         // Eliminate other pages not in pattern            
         if (! ereg($pattern,$fname)) continue;            
         $timedat = filemtime("$dir/$fname");            
         if ($timedat > $newstamp) {
            $newstamp = $timedat;
            $newname = $fname;
          }
         }
        }
closedir ($handle);

// $newstamp is the time for the latest file
// $newname is the name of the latest file
// print last mod.file - format date as you like            
print $newname . " - " . date( "Y/m/d", $newstamp); 

答案 4 :(得分:1)

以下是使用DirectoryIterator的方法:

foreach(new DirectoryIterator('/path/to/read') as $item) {
    if ($item->isFile() && (empty($file) || $item->getMTime() > $file->getMTime())) {
        $file = clone $item;
    }
}

$file的结果内容是DirectoryIterator类的一个实例,因此您可以访问其所有方法。要简单地获取结果的完整路径,您可以执行以下操作:

echo $file->getPathname();

答案 5 :(得分:0)

枚举所有目录文件,获取每个目录文件的filemtime()并完成。

答案 6 :(得分:0)

如果在linux上工作,请查看http://us2.php.net/manual/en/book.inotify.php。这假设你让脚本等待&在后台记录这些事件。

答案 7 :(得分:0)

我的PHP 5解决方案:

$dir = "/path/to/Your/dir"; 
$arraydir =scandir($dir, 1);
echo "arraydir 0: " . $arraydir[0] . "<br/>"; // 1. new file
echo "arraydir 1: " . $arraydir[1] . "<br/>"; // 2. new file
echo "arraydir elements: " . count($arraydir) . "<br/>";

(搜索单词DE:neuste und zweitneuste Datei eines Ordners anzeigen mit PHP)