Delete temporary files


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

This example shows how to delete specific files after a given time span.
This works good for cleaning cached files.


Copy this code and paste it in your HTML
  1. // Define the folder to clean
  2. // (keep trailing slashes)
  3. $captchaFolder = 'temp/';
  4.  
  5. // Filetypes to check (you can also use *.*)
  6. $fileTypes = '*.jpg';
  7.  
  8. // Here you can define after how many
  9. // minutes the files should get deleted
  10. $expire_time = 20;
  11.  
  12. // Find all files of the given file type
  13. foreach (glob($captchaFolder . $fileTypes) as $Filename) {
  14.  
  15. // Read file creation time
  16. $FileCreationTime = filectime($Filename);
  17.  
  18. // Calculate file age in seconds
  19. $FileAge = time() - $FileCreationTime;
  20.  
  21. // Is the file older than the given time span?
  22. if ($FileAge > ($expire_time * 60)){
  23.  
  24. // Now do something with the olders files...
  25.  
  26. print "The file $Filename is older than $expire_time minutes\n";
  27.  
  28. // For example deleting files:
  29. //unlink($Filename);
  30. }
  31.  
  32. }

URL: http://www.jonasjohn.de/snippets/php/delete-temporary-files.htm

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.