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

前端 未结 3 1934
南方客
南方客 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);
    

提交回复
热议问题