How to list files in a directory in "last modified date" order? (PHP5 on Linux)
function newest($a, $b)
{
return filemtime($a) - filemtime($b);
}
$dir = glob('files/*'); // put all files in an array
uasort($dir, "newest"); // sort the array by calling newest()
foreach($dir as $file)
{
echo basename($file).'<br />';
}
Credit goes here.
Try that same query on google and you'll get answers faster. Cheers. http://php.net/manual/en/function.filemtime.php
Another one from Google: http://www.php.net/manual/en/function.sort.php#76198
A solution would be to :
DirectoryIterator
, for instanceSplFileInfo::getMTime
asort
or arsort
-- depending on the order in which you want your files.
For example, this portion of code :
$files = array();
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$files[$fileinfo->getFilename()] = $fileinfo->getMtime();
}
}
arsort($files);
var_dump($files);
Gives me :
array
'temp.php' => int 1268342782
'temp-2.php' => int 1268173222
'test-phpdoc' => int 1268113042
'notes.txt' => int 1267772039
'articles' => int 1267379193
'test.sh' => int 1266951264
'zend-server' => int 1266170857
'test-phing-1' => int 1264333265
'gmaps' => int 1264333265
'so.php' => int 1264333262
'prepend.php' => int 1264333262
'test-curl.php' => int 1264333260
'.htaccess' => int 1264333259
i.e. the list of files in the directory where my script is saved, with the most recently modified at the beginning of the list.
read files in a directory by using readdir
to an array along with their filemtime
saved. Sort the array based on this value, and you get the results.