How to get X newest files from a directory in PHP?

前端 未结 3 1931
南方客
南方客 2020-12-19 08:12

The code below is part of a function for grabbing 5 image files from a given directory.

At the moment readdir returns the images \'in the order in which they are sto

相关标签:
3条回答
  • 2020-12-19 08:21

    If you want to do this entirely in PHP, you must find all the files and their last modification times:

    $images = array();
    foreach (scandir($folder) as $node) {
        $nodePath = $folder . DIRECTORY_SEPARATOR . $node;
        if (is_dir($nodePath)) continue;
        $images[$nodePath] = filemtime($nodePath);
    }
    arsort($images);
    $newest = array_slice($images, 0, 5);
    
    0 讨论(0)
  • 2020-12-19 08:24

    If you are really only interested in pictures you could use glob() instead of soulmerge's scandir:

    $images = array();
    foreach (glob("*.{png,jpg,jpeg}", GLOB_BRACE) as $filename) {
        $images[$filename] = filemtime($filename);
    }
    arsort($images);
    $newest = array_slice($images, 0, 5);
    
    0 讨论(0)
  • 2020-12-19 08:42

    Or you can create function for the latest 5 files in specified folder.

    private function getlatestfivefiles() {
        $files = array();
        foreach (glob("application/reports/*.*", GLOB_BRACE) as $filename) {
            $files[$filename] = filemtime($filename);
        }
        arsort($files);
    
        $newest = array_slice($files, 0, 5);
        return $newest;  
    }
    

    btw im using CI framework. cheers!

    0 讨论(0)
提交回复
热议问题