Get last modified file in a directory

前端 未结 4 1983
时光说笑
时光说笑 2020-11-30 10:23

Is there a way to select only the last file in a directory (with the extensions jpg|png|gif?)

Or do I have to parse the entire directory and check using

4条回答
  •  情书的邮戳
    2020-11-30 10:38

    I don't remember having ever seen a function that would do what you ask.

    So, I think you will have to go through all (at least jpg/png/gif) files, and search for the last modification date of each of them.


    Here's a possible solution, based on the DirectoryIterator class of the SPL :

    $path = null;
    $timestamp = null;
    
    $dirname = dirname(__FILE__);
    $dir = new DirectoryIterator($dirname);
    foreach ($dir as $fileinfo) {
        if (!$fileinfo->isDot()) {
            if ($fileinfo->getMTime() > $timestamp) {
                // current file has been modified more recently
                // than any other file we've checked until now
                $path = $fileinfo->getFilename();
                $timestamp = $fileinfo->getMTime();
            }
        }
    }
    
    var_dump($path);
    


    Of course, you could also do the same thing with readdir() and other corresponding functions.

提交回复
热议问题