List All Files In A Directory By Creation Date

25th May 2008 - 2 minutes read time

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.

  1. function listDirectoryByDate($path) {
  2. $dir = opendir($path);
  3. $list = array();
  4. while ($file = readdir($dir)) {
  5. if ($file != '.' && $file != '..' && !is_dir($file)) {
  6. $ctime = filectime($path.$file) . rand(1000,9999);
  7. $list[$ctime] = $file;
  8. }
  9. }
  10. closedir($dir);
  11. krsort($list);
  12. return $list;
  13. }

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.