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.

function deleteTemporaryFiles()
{
 // Define the folder to clean (keep trailing slashes)
 $dataFolder  = 'data/';
 
 // Filetypes to check - use glob syntax
 $fileTypes = '*.{txt,xml}';
 
 // Here you can define after how many minutes the files should get deleted
 $expire_time = 20;
 
 // Find all files of the given file type
 foreach ( glob($dataFolder.$fileTypes,GLOB_BRACE) as $Filename ) {
  // Read file creation time
  $FileCreationTime = filectime($Filename);
 
  // Calculate file age in seconds
  $FileAge = time() - $FileCreationTime;
 
  // Is the file older than the given time span?
  if ( $FileAge > ($expire_time * 60) ) {
   // delete the file
   unlink($Filename);
  }
 }
}

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().

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
8 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.