Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting files by creation/modification date in PHP [duplicate]

Tags:

php

Possible Duplicate:
File creation time

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.

like image 209
Roberto Aloi Avatar asked Feb 24 '10 11:02

Roberto Aloi


4 Answers

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);
  }
}
like image 53
knittl Avatar answered Oct 06 '22 20:10

knittl


That's my solution:

$fileList = array();
$files = glob('home/dir/*.txt');
foreach ($files as $file) {
    $fileList[filemtime($file)] = $file;
}
ksort($fileList);
$fileList = array_reverse($fileList, TRUE);
print_r($filelist);

output is like this:

array(
    (int) 1340625301 => '/home/dir/file15462.txt',
    (int) 1340516112 => '/home/dir/file165567.txt',
    (int) 1340401114 => '/home/dir/file16767.txt'
)

Then with "foreach" loop take the file you need.

like image 36
trante Avatar answered Oct 06 '22 20:10

trante


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"
}
like image 25
soulmerge Avatar answered Oct 06 '22 20:10

soulmerge


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);
like image 27
Pekka Avatar answered Oct 06 '22 19:10

Pekka