Posted By

fackz on 02/12/09


Tagged

sort dir files directory


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

xtheonex
fackz
pster
BrianCoyDesign


Sort files from directory & order them by filemtime()


 / Published in: PHP
 

URL: http://www.bitrepository.com/web-programming/php/sort-files-by-filemtime.html

This is a function that selects files from a directory and orders them by the last time they were changed, in ascending or descending order. The snippet also calculates how much time passed since the file’s content was changed.

  1. function Sort_Directory_Files_By_Last_Modified($dir, $sort_type = 'descending', $date_format = "F d Y H:i:s.")
  2. {
  3. $files = scandir($dir);
  4.  
  5. $array = array();
  6.  
  7. foreach($files as $file)
  8. {
  9. if($file != '.' && $file != '..')
  10. {
  11. $now = time();
  12. $last_modified = filemtime($dir.$file);
  13.  
  14. $time_passed_array = array();
  15.  
  16. $diff = $now - $last_modified;
  17.  
  18. $days = floor($diff / (3600 * 24));
  19.  
  20. if($days)
  21. {
  22. $time_passed_array['days'] = $days;
  23. }
  24.  
  25. $diff = $diff - ($days * 3600 * 24);
  26.  
  27. $hours = floor($diff / 3600);
  28.  
  29. if($hours)
  30. {
  31. $time_passed_array['hours'] = $hours;
  32. }
  33.  
  34. $diff = $diff - (3600 * $hours);
  35.  
  36. $minutes = floor($diff / 60);
  37.  
  38. if($minutes)
  39. {
  40. $time_passed_array['minutes'] = $minutes;
  41. }
  42.  
  43. $seconds = $diff - ($minutes * 60);
  44.  
  45. $time_passed_array['seconds'] = $seconds;
  46.  
  47. $array[] = array('file' => $file,
  48. 'timestamp' => $last_modified,
  49. 'date' => date ($date_format, $last_modified),
  50. 'time_passed' => $time_passed_array);
  51. }
  52. }
  53.  
  54. usort($array, create_function('$a, $b', 'return strcmp($a["timestamp"], $b["timestamp"]);'));
  55.  
  56. if($sort_type == 'descending')
  57. {
  58. krsort($array);
  59. }
  60.  
  61. return array($array, $sort_type);
  62. }
  63.  
  64. //Example of usage:
  65.  
  66. $dir = '/home/public_html/my_directory/';
  67.  
  68. $array = Sort_Directory_Files_By_Last_Modified($dir);
  69.  
  70. // Info Array
  71. $info = $array[0];
  72.  
  73. // Sort Type
  74. $sort_type = $array[1];
  75.  
  76. echo '<h3>'.$dir.'</h3>';
  77.  
  78. echo 'Order by: Last Modified ('.$sort_type.')<br>';
  79.  
  80. foreach($info as $key => $detail)
  81. {
  82. echo '<h4>'.$detail['file'].'</h4>';
  83.  
  84. echo 'Last Modified: '.$detail['date'].'<br>';
  85.  
  86. $time_passed = '';
  87.  
  88. foreach($detail['time_passed'] as $type => $value)
  89. {
  90. $time_passed .= $value." ".$type.", ";
  91. }
  92.  
  93. $time_passed = "<span>".rtrim($time_passed, ", ")."</span> ago";
  94.  
  95. echo $time_passed."nn";
  96.  
  97. }

Report this snippet  

You need to login to post a comment.