How to Get the Newest File in a Directory in PHP

How to get the newest file in a directory in php

Here's an attempt using scandir, assuming the only files in the directory have timestamped filenames:

$files = scandir('data', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];

We first list all files in the directory in descending order, then, whichever one is first in that list has the "greatest" filename — and therefore the greatest timestamp value — and is therefore the newest.

Note that scandir was added in PHP 5, but its documentation page shows how to implement that behavior in PHP 4.

Get the latest file addition in a directory

$path = "/path/to/my/dir"; 

$latest_ctime = 0;
$latest_filename = '';

$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}

// now $latest_filename contains the filename of the file that changed last

Get the latest file addition in a directory

$path = "/path/to/my/dir"; 

$latest_ctime = 0;
$latest_filename = '';

$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}

// now $latest_filename contains the filename of the file that changed last

How to get newest file in remote folder PHP?

You need to replace this code:

$path = "http://wwww.site.com/myfolder";

With this:

$path = "myfolder"; 

Get latest file in dir including subdirectory php

To the best of my knowledge, you have to recursively check every folder and file to get the last modified file. And you're current solution doesn't check the last modified file but sorts the files in descending order by name.

Meaning if you have a 10 years old file named z.txt it will probably end up on top.

I've cooked up a solution.

  1. The function accepts a directory name and makes sure the directory
    exists. It returns null when the directory has no files or any of its subdirectories.
  2. Sets aside the variables $latest and $latestTime where the last modified file is stored.
  3. It loops through the directory, avoiding the . and .. since they can cause an infinite recursion loop.
  4. In the loop the full filename is assembled from the initial directory name and the part.
  5. The filename is checked if it is a directory if so it calls the same function we are in and saves the result.
  6. If the result is null we continue the loop otherwise we save the file as the new filename, which we now know is a file.
  7. After that we check the last modified time using filemtime and see if the $latestTime is smaller meaning the file was modified earlier in time that the current one.
  8. If the new file is indeed younger we save the new values to $latest and $latestTime where $latest is the filename.
  9. When the loop finishes we return the result.
function find_last_modified_file(string $dir): ?string
{
if (!is_dir($dir)) throw new \ValueError('Expecting a valid directory!');

$latest = null;
$latestTime = 0;
foreach (scandir($dir) as $path) if (!in_array($path, ['.', '..'], true)) {
$filename = $dir . DIRECTORY_SEPARATOR . $path;

if (is_dir($filename)) {
$directoryLastModifiedFile = find_last_modified_file($filename);

if (null === $directoryLastModifiedFile) {
continue;
} else {
$filename = $directoryLastModifiedFile;
}
}

$lastModified = filemtime($filename);
if ($lastModified > $latestTime) {
$latestTime = $lastModified;
$latest = $filename;
}
}

return $latest;
}

echo find_last_modified_file(__DIR__);

In step 7 there is an edge case if both files were modified at the exact same time this is up to you how you want to solve. I've opted to leaving the initial file with that modified time instead of updating it.

Get last modified file in a directory

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);

Get the newest file from directory structure year/month/date/time

Well, you can fetch whole directory tree at once and get last elem from it:

$baseFolder = './backup_mini' ;

$arr = glob("{$baseFolder}/*/*/*/*", GLOB_ONLYDIR);
$lastDir = array_pop($arr);


Related Topics



Leave a reply



Submit