tags:

views:

326

answers:

6

In PHP, how to retrieve the files contained into a folder sorted by creation date (or any other sorting mechanism)?

According to the doc, the readdir() function:

The filenames are returned in the order in which they are stored by the filesystem.

+4  A: 

save their information to an array, sort the array and then loop the array

if($h = opendir($dir)) {
  $files = array();
  while(($file = readdir($h) !== FALSE)
    $files[] = stat($file);

  // do the sort
  usort($files, 'your_sorting_function');

  // do something with the files
  foreach($files as $file) {
    echo htmlspecialchars($file);
  }
}
knittl
A: 

Heh, not even the great DirectoryIterator can do that out of the box. Sigh.

There seems to be a pretty powerful script to do all that referenced here: preg_find. I've never worked with it but it looks good.

sorted in by filesize, in descending order?
$files = preg_find('/./', $dir,
  PREG_FIND_RECURSIVE| PREG_FIND_RETURNASSOC |
  PREG_FIND_SORTFILESIZE|PREG_FIND_SORTDESC);

$files=array_keys($files);
Pekka
A: 

You could use scandir() to read the contents of the directory into an array, then use fileatime() or filectime() to see each file's access or creation time, respectively. Sorting the array from here shouldn't be too hard.

jackbot
+1  A: 

You can store the files in an array, where the key is the filename and the value is the value to sort by (i.e. creation date) and use asort() on that array.

$files = array(
    'file1.txt' => 1267012304,
    'file3.txt' => 1267011892,
    'file2.txt' => 1266971321,
);
asort($files);
var_dump(array_keys($files));
# Output:
array(3) {
  [0]=>
  string(9) "file2.txt"
  [1]=>
  string(9) "file3.txt"
  [2]=>
  string(9) "file1.txt"
}
soulmerge
A: 

use shell_exec to execute command on os-level? on a linux/unix box this might work;

$output=shell_exec('ls -t1');
futtta
… please don't.
knittl
+1  A: 

From my answer at http://stackoverflow.com/questions/2084986/file-creation-time

function sortByChangeTime($file1, $file2)
{
    return (filectime($file1) < filectime($file2)); 
}
$files = glob('*.*');              // use scandir if you want hidden files too
usort($files, 'sortByChangeTime'); // sort by callback
var_dump($files);                  // dump sorted file list

Note that filectime will return Change Time on Linux and Creation Time on Windows. You cannot get creation time on Linux systems.

Gordon
clever usage of `glob`. this will not match hidden files though …
knittl
@knittl it will find hidden files on Windows
Gordon
i'm talking about hidden files on linux, starting with a period like `.htaccess`
knittl
@knittl true, but the above approach wouldn't give the OP what he asked for on Linux anyway. You cannot get file creation time on Linux through PHP.
Gordon
@gordon creation time was only an example given by the OP. replace `glob` with `scandir` and we're good ;)
knittl
@knittl ok, added it in the comment
Gordon