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.
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);
}
}
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.
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"
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With