Main Content

Most recent file in a directory - PHP

Archive - Originally posted on "The Horse's Mouth" - 2006-12-18 07:16:59 - Graham Ellis

Want to report the most recently updated file in a directory in PHP? It's the sort of thing we all want to do, but in a variety of modified forms, quite often ... here's a code snippet to do it for you:

$dir = "/home/wellho/public_html/demo";
$pattern = '\.(html|php|php4)$';

$newstamp = 0;
$newname = "";
$dc = opendir($dir);
while ($fn = readdir($dc)) {
  # Eliminate current directory, parent directory
  if (ereg('^\.{1,2}$',$fn)) continue;
  # Eliminate other pages not in pattern
  if (! ereg($pattern,$fn)) continue;
  $timedat = filemtime("$dir/$fn");
  if ($timedat > $newstamp) {
    $newstamp = $timedat;
    $newname = $fn;
  }
}
# $timedat is the time for the latest file
# $newname is the name of the latest file


You'll note that I have provided separate varaibles for the directory to be searched and a regular expression that's to be used for filtering file names - you'll always want to skip over . and .., and you'll normally want to ensure that backup files, hidden data, etc, don't get logged.

The code that uses $newname and $timedat later on needs to take care of the case in which they're null / empty - i.e. if you've looked through a directory that didn't contain anything.

The source code is available here in full, and you can run the script here. Note that the time / date report is the server time / date and not the time / date from the country you happen to be browsing in.