Jump to content

Sorting files by date and returning just the file name


gibbo1715

Recommended Posts

Hi All

 

Still pretty new to PHP so I hope this isnt too much of a daft question

 

I need to loop through some files and return the result with the most recently created first, I think i ve found a way to list the items by date order but I cant figure out how to return just the file name, might also be that im returning the values with the oldest first actually, not checked yet, Can anyone assist please

 

thanks

 

gibbo

 




<?php

$path = './js/';
$list = listdir_by_date($path);


foreach($list as $key => $value) {
   print "$key: $value<br>";
}

function listdir_by_date($path){
$dir = opendir($path);
$list = array();
while($file = readdir($dir)){
if ($file != '.' and $file != '..'){
// add the filename, to be sure not to
// overwrite a array key
$ctime = filectime($path . $file) . ',' . $file;
$list[$ctime] = $file;
}
}
closedir($dir);
krsort($list);
return $list;
}


?>

Thankyou for your replies, it is currently on a linux server but may end up on a microsoft one, Last modified is also fine for me so i d be interested if there is a way to order by either of those in a different way.

 

Many Thanks for your help

 

Gibbo

 

Let's say you have all the filenames in the array $files. So your job is to get all the file names and store then into that array. Make sure they have the correct path of the file so that filemtime can reference it.

 

<?php
function LastModifiedCompare ($a, $b) {
     return filemtime($a) > filemtime($b);
}

usort($files, 'LastModifiedCompare');

var_dump($files); // list all of them starting from most recent modified to last.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.