Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

php

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 stored by the filesystem' as per the spec.

My question is, how can I modify it to get the latest 5 images? Either based on the last_modified date or the filename (which look like 0000009-16-5-2009.png, 0000012-17-5-2009.png, etc.).

if ( $handle = opendir($absolute_dir) )
{
    $i = 0;
    $image_array = array();

    while ( count($image_array) < 5 && ( ($file = readdir($handle)) !== false) )
    {
        if ( $file != "." && $file != ".." && $file != ".svn" && $file != 'img' ) 
        {
            $image_array[$i]['url'] = $relative_dir . $file;
            $image_array[$i]['last_modified'] = date ("F d Y H:i:s", filemtime($absolute_dir . '/' . $file));
        }

        $i++;
    }
    closedir($handle);
}
like image 269
meleyal Avatar asked Jun 19 '09 13:06

meleyal


3 Answers

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);
like image 146
soulmerge Avatar answered Sep 18 '22 23:09

soulmerge


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!

like image 25
nothingchen01 Avatar answered Sep 22 '22 23:09

nothingchen01


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);
like image 37
nietonfir Avatar answered Sep 20 '22 23:09

nietonfir