PHP: ordered directory listing

How to list files in a directory in order of "last modified date"? (PHP5 on Linux)

+4
php
source share
5 answers
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 .

+14
source share

read files in a directory using readdir for an array along with saved filemtime . Sort the array based on this value and you will get the results.

+3
source share

The solution would be:

  • Iterating over files in a directory - using DirectoryIterator , for example
  • For each file, get its latest modification time using SplFileInfo::getMTime
  • Put it all in an array using:
    • file names in the form of keys
    • Modification time as values
  • And sort the array using asort or arsort - depending on the order in which you want to store the files.


For example, this piece 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. a list of files in the directory where my script is saved, with the last one changed at the top of the list.

+1
source share

Try the same query on google and you will get answers faster. Greetings. http://php.net/manual/en/function.filemtime.php

0
source share
0
source share

All Articles