How to list files in a directory in "last modified date" order? (PHP5 on Linux)
+1
A:
Try that same query on google and you'll get answers faster. Cheers. http://php.net/manual/en/function.filemtime.php
ign
2010-03-11 21:26:49
+1
A:
Another one from Google: http://www.php.net/manual/en/function.sort.php#76198
Ztyx
2010-03-11 21:28:40
+1
A:
A solution would be to :
- Iterate over the files in the directory -- using
DirectoryIterator
, for instance - For each file, get its last modification time, using
SplFileInfo::getMTime
- Put all that in an array, with :
- the files names as keys
- The modification times as values
- And sort the array, with either
asort
orarsort
-- 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.
Pascal MARTIN
2010-03-11 21:29:07
+2
A:
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.
Pentium10
2010-03-11 21:29:24
+5
A:
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.
ChristopheD
2010-03-11 21:29:46
to compare numeric values simply subtract them: return filemtime($a) - filemtime($b);
stereofrog
2010-03-11 23:46:45
@stereofrog: good point, thanks (edited the answer)
ChristopheD
2010-03-12 00:08:43