Posted By

fackz on 03/25/09


Tagged

delete dir files days


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

fackz
rombob
Some0ne
Priestd09


Script to delete files in a directory (X days old)


 / Published in: PHP
 

delete all files in a directory that are more than 7 days old.

  1. <?php
  2.  
  3. $dir = '/path/to/dir';
  4. if ($handle = opendir($dir)) {
  5. /* This is the correct way to loop over the directory. */
  6. while (false !== ($file = readdir($handle))) {
  7. if ($file[0] == '.' || is_dir("$dir/$file")) {
  8. // ignore hidden files and directories
  9. continue;
  10. }
  11. if ((time() - filemtime($file)) > ($days *86400)) { //7 days
  12. unlink("$dir/$file");
  13. }
  14. }
  15. closedir($handle);
  16. }

Report this snippet  

You need to login to post a comment.