dynamic
dynamic

Reputation: 48101

Get last modified file in a directory

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 filemtime?

Upvotes: 19

Views: 35419

Answers (4)

Shamsher Sidhu
Shamsher Sidhu

Reputation: 93

Use this code:

<?php
// outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>

Upvotes: 2

mario
mario

Reputation: 145482

Yes you have to read through them all. But since directory accesses are cached, you shouldn't really worry about it.

$files = array_merge(glob("img/*.png"), glob("img/*.jpg"));
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);

$latest_file = key($files);

Upvotes: 51

Waqar Alamgir
Waqar Alamgir

Reputation: 9968

function listdirfile_by_date($path)
{
    $dir = opendir($path);
    $list = array();
    while($file = readdir($dir))
    {
        if($file != '..' && $file != '.')
        {
            $mtime = filemtime($path . $file) . ',' . $file;
            $list[$mtime] = $file;
        }
    }
    closedir($dir);
    krsort($list);

    foreach($list as $key => $value)
    {
        return $list[$key];
    }
    return '';
}

Upvotes: 2

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

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`**][1] 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()`**][2] and other corresponding functions.

Upvotes: 6

Related Questions