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.
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);
}
}
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);
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.
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"
}
use shell_exec to execute command on os-level? on a linux/unix box this might work;
$output=shell_exec('ls -t1');
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.