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


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.