递归浏览所有服务器目录并使用 php 列出最新创建的文件


Recursive browse all server directories and list newest created files with php

非常常见的问题,但仍然没有找到正确的解决方案。我需要每天早上运行 cron 作业来启动 php 脚本,以列出夜间在 Web 服务器上创建的所有新文件。这对于查看访问者在夜间上传的内容非常有用,当然这些文件可能是有害文件,会伤害其他访问者的计算机。到目前为止,我有这个:

$dir = "../root/";         
$pattern = ''.*$'; // 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);    

这将打印最新的文件,但仅在一个目录根/中,并且不检查例如根/文件夹/等。怎么回避呢?如果我在根/文件夹中添加一个新文件,脚本将向我显示带有日期的文件夹,但不会显示根/文件夹中的哪个文件已创建。我希望你明白我的意思,谢谢

快速脚本,可以做你想要的(在Windows 7和Ubuntu 12.10和PHP 5.3.10下测试)

<?php
$path = $argv[1];
$since = strtotime('-10 second'); // use this for previous day: '-1 day'
$ite = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
foreach ( new RecursiveIteratorIterator($ite) as $filename => $object ) {
    if (filemtime($filename) > $since) {
      echo "$filename recently created'n";
    }
}

我的快速测试:

$> mkdir -p d1/d2
$> touch d1/d2/foo
$> php test.php .
./d1/d2/foo recently created
$> php test.php . # 10secs later 
$>