tags:

views:

60

answers:

5

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
+1  A: 

Another one from Google: http://www.php.net/manual/en/function.sort.php#76198

Ztyx
+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 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.

Pascal MARTIN
+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
+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
to compare numeric values simply subtract them: return filemtime($a) - filemtime($b);
stereofrog
@stereofrog: good point, thanks (edited the answer)
ChristopheD