简体   繁体   中英

Get filemtime for most recently updated file in folder

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?

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();
        }
    }
}

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.

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