【问题标题】:Recursive browse all server directories and list newest created files with php递归浏览所有服务器目录并使用 php 列出最新创建的文件
【发布时间】:2013-01-12 20:34:12
【问题描述】:

非常常见的问题,但仍然没有找到正确的解决方案。我需要每天早上运行 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);    

这将打印最新的文件,但仅在一个目录 root/ 中,并且不检查例如 root/folder/ 等。如何重新执行? 如果我在根/文件夹中添加一个新文件,脚本将显示带有日期的文件夹,但不会显示在根/文件夹中创建了哪个文件。希望你明白我的意思,谢谢

【问题讨论】:

  • 当用户上传文件时,我会更简单地进行检查。
  • 当我们谈论 300-400 个文件时并不容易..

标签: php file


【解决方案1】:

执行所需的快速脚本(在 windows 7 下使用 cygwin 和 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 
$>

【讨论】:

  • Cears pinouchon,但我收到此错误致命错误:在我使用 php 4 中找不到类“FilesystemIterator”
  • +1,虽然在使用 SPL 类时为什么要使用 filemtime()?你可以使用$filename-&gt;getMTime()。我也宁愿看到DateTime 对象而不是strtotime()。但无论如何 +1,因为这几乎是我会做的。
  • @Мариян Маринов - FilesystemIterator 内置于 PHP 5.3 及更高版本中,请参阅 php.net/manual/en/class.filesystemiterator.php。如果您使用的是旧版本,则应该升级,因为不支持任何早于 5.3 的版本。但是如果你不能升级,这个答案仍然可以在没有FilesystemIterator 位的情况下使用。
  • @МариянМаринов 在if (filemtime($filename) &gt; $since) 之前打印 $filename 看看会发生什么。
  • 对不起 pinouchon,你是对的,我只需要更改 -1 秒,这就是为什么没有看到所有文件,但是否也可以显示文件的创建时间?
猜你喜欢
  • 2016-04-02
  • 1970-01-01
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 2017-10-31
  • 2014-07-07
  • 2010-10-04
相关资源
最近更新 更多