Reputation:
I am using the code below to echo out all the files from a directory onto a page. The order of the files that are echoed out are in a random order, i.e,
File 3
File 1
File 2
Instead of
File 1
File 2
File 3
How do I make it so that the files that are echoed out are based on when it was created or uploaded. The most recent files will appear at the top of the list, and the oldest file will appear at the bottom
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo "<p>$entry\n</p>";
}
}
closedir($handle);
}
Upvotes: 1
Views: 402
Reputation: 59681
This should work for you:
(Here i get all files from a directory with glob()
, then i sort it with a user defined function usort()
and compare the times of the last modification with filemtime()
)
<?php
function cmp($a, $b) {
if (filemtime($a) == filemtime($b))
return 0;
return (filemtime($a) < filemtime($b)) ? -1 : 1;
}
$files = glob("*.*");
usort($files, "cmp");
foreach($files as $file)
echo $file . "<br />";
?>
Upvotes: 2
Reputation: 159
Next time try to search on stackoverflow for questions similar to yours :)
$files = array();
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort ksort($files); // find the last modification $reallyLastModified = end($files);
foreach($files as $file) { $lastModified = date('F d Y, H:i:s',filemtime($file)); if(strlen($file)-strpos($file,".swf")== 4){ if ($file == $reallyLastModified) { // do stuff for the real last modified file } echo "$file$lastModified"; } }
Not tested
Upvotes: 0
Reputation: 439
Take a look at PHP4+'s filemtime. You're going to want to do 2 things here:
Upvotes: 0