4

I have a folder with 4 files in it and I'd like to pull the last modified time of the most recent one (which may not always be the same one). Is there a good way to do that?

ryanve
  • 50,076
  • 30
  • 102
  • 137
  • 1
    Iterate through all the files, hanging on to the one with the latest modified time. Display the result at the end. – Brad Jul 20 '11 at 19:29

2 Answers2

6

Use a DirectoryIterator to find the files and then simply compare their modified times. This oughta do it:

$iterator = new DirectoryIterator('path/to/dir');

$mtime = -1;
$file;
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        if ($fileinfo->getMTime() > $mtime) {
            $file = $fileinfo->getFilename();
            $mtime = $fileinfo->getMTime();
        }
    }
}
David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
3

There is no need to iterate through the directory - filemtime will work for most servers, (depending on your configuration):

$LastMod = filemtime("/path/to/dir/.");

The last dot is needed to see the directory as a file and to actually get a last modification date of it.

cronoklee
  • 6,482
  • 9
  • 52
  • 80
  • According server configuration lastmod on directories will be updated according children files... or not :( – davidmars Aug 15 '15 at 04:40
  • Using PHP7 on an Ubuntu server getting filemtime on a folder will result in `Warning: filemtime(): stat failed for [folder]` – patrick Jun 21 '20 at 00:22