Reputation: 1069
My data.txt is generated each time when someone is visiting my site. I would like to delete this file on on specific time, let say 1:00AM daily. I found this script but I'm struggling to update the code :/ Any advice?
<?php
$path = dirname(__FILE__).'/files';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ((time()-filectime($path.'/'.$file)) < 86400) { // 86400 = 60*60*24
if (preg_match('/\.txt$/i', $file)) {
unlink($path.'/'.$file);
}
}
}
}
?>
Upvotes: 0
Views: 991
Reputation: 37365
Use task scheduler, such as cron for this purposes. You can remove your file simply via shell command
rm /path/to/data.txt
So there's no need to write a PHP script for that.
Upvotes: 1
Reputation: 55760
The script you posted deletes .txt files in the given folder if they are older than a day but the problem is that this test only happens once - when you run the script.
What you need to do is run this script periodically. If you are running this on Linux you should probably add a cron job that executes this script periodically, say once an hour or once daily.
If you're running this on Windows, there is a task schedule that you could use to accomplish the same thing.
Upvotes: 1