How to Check Last Modified Date For All Files in a Folder with PHP

By | March 28, 2009

This function will help you if you need to monitor folders for recently changed files, or you may implement it as an anti-hacker solution to check your files. Anyway, I think you find it useful.

<?

//Put here the directory you want to search for. Put / if you want to search your entire domain
$dir=’/var/www/html/domain.com/download’;

//Put the date you want to compare with in the format of:  YYYY-mm-dd hh:mm:ss
$comparedatestr=”2009-03-25 00:00:00″;
$comparedate=strtotime($comparedatestr);

//I run the function here to start the search.
$go=modified_time($dir,$comparedate);

var_dump($go);

//This is the function which is doing the search…
function modified_time($address,$comparedate){

$files=array();
@$dir = opendir($address);

if(!$dir){ return 0; }
while($entry = readdir($dir)){
if(is_dir(“$address/$entry”) && ($entry != “..” && $entry != “.”)){
modified_time(“$address/$entry”,$comparedate);
}
else   {

if($entry != “..” && $entry != “.”) {

$fulldir=$address.’/’.$entry;
$last_modified = filemtime($fulldir);
$last_modified_str= date(“Y-m-d h:i:s”, $last_modified);

if($comparedate < $last_modified)  {
$files[$fulldir]=$last_modified_str;
}

}

}

}

return($files);

}
?>

In the sample above we’re getting the list of files that are older than the specified date into an array. We’re taking file paths into array keys and modification dates into values. I’ve performed var_dump to show the structure of this array. The original code of this function was found at PHP website.  Hope you like it.