List All Files In A Directory By Creation Date

The following function takes a path as an argument and produces an array of files ordered by their timestamp. The array values are the filename and the array keys are the timestamps. In order to prevent two files that have the same timestamp overwriting each other when the array keys are created with a random number. If two files where created at the same time the least that will happen is that they will swap places every time the array is created as the random number will be different.

function listDirectoryByDate($path) {
 $dir = opendir($path);
 $list = array();
 while ($file = readdir($dir)) {
  if ($file != '.' && $file != '..' && !is_dir($file)) {
   $ctime = filectime($path.$file) . rand(1000,9999);
   $list[$ctime] = $file;
  }
 }
 closedir($dir);
 krsort($list);
 return $list;
}

To use the function to print out all of the files in the current directory use the following code.

echo '<pre>'.print_r(listDirectoryByDate('./'),true).'</pre>';

Note that the filectime() function can give an incorrect value on some Win32 systems by returning the file creation time. This is what we are looking for, but if you find you are having problems with this function then replace filectime() with filemtime().

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.