GarbageCollect.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Gregwar\Image;
  3. /**
  4. * Garbage collect a directory, this will crawl a directory, lookng
  5. * for files older than X days and destroy them
  6. *
  7. * @author Gregwar <g.passault@gmail.com>
  8. */
  9. class GarbageCollect
  10. {
  11. /**
  12. * Drops old files of a directory
  13. *
  14. * @param string $directory the name of the target directory
  15. * @param int $days the number of days to consider a file old
  16. * @param bool $verbose enable verbose output
  17. *
  18. * @return true if all the files/directories of a directory was wiped
  19. */
  20. public static function dropOldFiles($directory, $days = 30, $verbose = false)
  21. {
  22. $allDropped = true;
  23. $now = time();
  24. $dir = opendir($directory);
  25. if (!$dir) {
  26. if ($verbose) {
  27. echo "! Unable to open $directory\n";
  28. }
  29. return false;
  30. }
  31. while ($file = readdir($dir)) {
  32. if ($file == '.' || $file == '..') {
  33. continue;
  34. }
  35. $fullName = $directory.'/'.$file;
  36. $old = $now-filemtime($fullName);
  37. if (is_dir($fullName)) {
  38. // Directories are recursively crawled
  39. if (static::dropOldFiles($fullName, $days, $verbose)) {
  40. self::drop($fullName, $verbose);
  41. } else {
  42. $allDropped = false;
  43. }
  44. } else {
  45. if ($old > (24*60*60*$days)) {
  46. self::drop($fullName, $verbose);
  47. } else {
  48. $allDropped = false;
  49. }
  50. }
  51. }
  52. closedir($dir);
  53. return $allDropped;
  54. }
  55. /**
  56. * Drops a file or an empty directory
  57. */
  58. public static function drop($file, $verbose = false)
  59. {
  60. if (is_dir($file)) {
  61. @rmdir($file);
  62. } else {
  63. @unlink($file);
  64. }
  65. if ($verbose) {
  66. echo "> Dropping $file...\n";
  67. }
  68. }
  69. }