Delete temporary files
This example shows how to delete specific files
after a given time span.
This works good for cleaning cached files.
// Define the folder to clean // (keep trailing slashes) $captchaFolder = 'temp/'; // Filetypes to check (you can also use *.*) $fileTypes = '*.jpg'; // 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($captchaFolder . $fileTypes) 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)){ // Now do something with the olders files... print "The file $Filename is older than $expire_time minutes\n"; // For example deleting files: //unlink($Filename); } }
Author:
Jonas John
License:
Public Domain
Language:
PHP
Created:
12/10/2007
Updated:
12/10/2007
Tags:
tutorials, directory functions, files
Related links:
Sorry folks, comments have been deactivated for now due to the large amount of spam.
Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!
Older comments:
I just had to add a ."*". in the middle of the glob function call.
<?php
// Define the folder to clean
// (keep trailing slashes)
$captchaFolder = 'E:temp';
// Filetypes to check (you can also use *.*)
$fileTypes = '*.*';
// Here you can define after how many
// minutes the files should get deleted
$expire_time = 5;
// Find all files of the given file type
foreach (glob($captchaFolder . $fileTypes) 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)){
// Now do something with the olders files...
print "The file $Filename is older than $expire_time minutesn";
// For example deleting files:
unlink($Filename);
}
}
echo 'ran';
?>