简体   繁体   中英

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

very common question and still did not find the right solution for this. I need to run cron job to start php script each morning to list all new files created on the web server during the night. This is very usefull to see what visitors have uploaded during the night and ofcourse very ofter those files could be harmful files that will hurt other visitors computers. So far I have this:

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

this prints the newest file but only in one directory root/ and doesnt check for example root/folder/ and etc.. How to do it recusrsivly ? If I add a new file within root/folder the script will show me folder with date , but would not show which file in root/folder was created.. I hope you understand what I mean, thanks

Quick script that does what you want (tested under windows 7 with cygwin and under ubuntu 12.10 with 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";
    }
}

My quick test:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM