How to get the newest file in a directory in php

For a search with wildcard you can use:

<?php
$path = "/var/www/html/*";

$latest_ctime = 0;
$latest_filename = '';

$files = glob($path);
foreach($files as $file)
{
        if (is_file($file) && filectime($file) > $latest_ctime)
        {
                $latest_ctime = filectime($file);
                $latest_filename = $file;
        }
}
return $latest_filename;
?>

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.

Tags:

Php

Directory