I'm trying to create a cron job which will automatically delete .jpg files from a particular folder that haven't been accessed for more than 5 days. Running the cron job is not a problem, but how do I go about writing the script which will take care of the deletion?
+3
A:
Assuming your filesystem is mounted with atime / relatime options you can use fileatime() to detect the last access time.
So something like:
$dir = '/your/path/';
if ($fh = opendir($dir))
{
while(($file = readdir($fh)) !== FALSE)
{
if ($file == '.' || $file == '..')
continue;
if (is_file($dir . $file) && fileatime($dir . $file) < strtotime('-5 days'))
unlink($dir . $file);
}
closedir($fh);
}
jasonbar
2010-03-27 05:57:25
If not tested (i.e. atime not implemented), your test will always evaluate to 0 < strtotime('-5 days'), which is always going to be true. Its better to store the result of fileatime() in another variable and check to ensure its not false prior to using it, else you'll delete every file in the directory :) Or, just test it once prior to doing any work.
Tim Post
2010-03-27 06:35:16