I was wondering if there was a way of using a script or some other option whereby I could automatically have files over a certain date deleted from my server.
I have created an AS3 eCard application whereby a php script writes a *.txt file to a folder with the relevant details of the message etc and would like to know if it’s possible to have files over ‘n’ days old automatically deleted some way to avoid cluttering up the site?
PHP Amendment :
<?php
if ($handle = opendir('/myFolder/holdingFolder')) {
while (false !== ($file = readdir($handle))) {
$filelastmodified = filemtime($file);
if((time() - $filelastmodified) > 14*24*3600)
{
unlink($file);
}
}
closedir($handle);
}
?>
I’m still learning php and would appreciate if anyone with more experience could look over this to point me in the right direction, if it’s the right way to go about deleting files in a folder after 14 days of creation?
If so, my server is windows/Plesk, would I need any special commands to run it and how often would you advise?
3
Answers
Based on what you have said, I think the easiest thing for you to get started with is a cron job and a php script.
Write a PHP script to loop the files checking creation date and delete the old ones. Then set up the PHP script on a cron job, which can run on any schedule you want.
There are of course 1000 ways to approach this, but it sounds like you already know PHP, and cron is available on any *nix system.
Here is a link to a random Google result for Crontab info and usage.
Try:
then run this script via a cron
If you’ve got access to cron, then you don’t need PHP – e,g, to to once a day….
If you don’t have access to cron, then run it as garbage collection as a shutdown function. E.g. (blatantly stealing Kyle Hudson’s code, although I note that he even copied the comments from here 😉