Friday, 10 August 2018

Function To Delete Temporary Files

If you allow users to upload data to your site you might have a situation where a data directory might be full of temporary files. In the long term you will want to get rid of these files as they have served their purpose and are no longer needed.
Here is a function that can be used to delete any files in a directory that were created more than 20 minutes ago. It uses the glob() function to find all files of a particular type and then uses the filectime() function to figure out when the file was last modified (or created). It will then delete (unlink) any files that were created more than 20 minutes ago.
  1. function deleteTemporaryFiles()
  2. {
  3. // Define the folder to clean (keep trailing slashes)
  4. $dataFolder = 'data/';
  5.  
  6. // Filetypes to check - use glob syntax
  7. $fileTypes = '*.{txt,xml}';
  8.  
  9. // Here you can define after how many minutes the files should get deleted
  10. $expire_time = 20;
  11.  
  12. // Find all files of the given file type
  13. foreach ( glob($dataFolder.$fileTypes,GLOB_BRACE) as $Filename ) {
  14. // Read file creation time
  15. $FileCreationTime = filectime($Filename);
  16.  
  17. // Calculate file age in seconds
  18. $FileAge = time() - $FileCreationTime;
  19.  
  20. // Is the file older than the given time span?
  21. if ( $FileAge > ($expire_time * 60) ) {
  22. // delete the file
  23. unlink($Filename);
  24. }
  25. }
  26. }
To use it simply call it like this.
deleteTemporaryFiles();
Note that the filectime() function can give an incorrect value on some Win32 systems by returning the file creation time. This is what we are looking for, but if you find you are having problems with this function then replace filectime() with filemtime().

0 comments:

Post a Comment