ok here is my workflow. I have a script that spits out xml files depending on what users are searching for. I am using time() to name them. I am doing this because I want each one to be unique. So right now I have all them going into a folder named xml. This is what I am trying to accomplish. I want to automatically delete the file say an hour later. I picked that time because I just want to make sure that I dont delete a file already in use. Is there a way to have a script runb say every hour. What I am thinking of doing is reading the folder and subtracting an hour in seconds and then compare the files that are older than that and then unlink them. It could probably be done with a foreach loop right? Well if there is a more simple solution I am more than willing to try it. Im all ears thanks
Yes just set up a cron job that runs the deleting script every 1 hour. If you don't have access to the cron job or if you want an even easier (but dirtier) way, just name the file with the current minute and second (e.g.: 0120 for 1st minute 20th second), and if another file is created the same second one or more hour later, just let it overwrite the older file. NOTE: with the above way, as well as with how you use time() for file names, you should consider what happens if more than 1 file is created within the same second.
both files and folder that files reside in need to be chmod to 0777 / 777 <?php if ($handle = opendir('.')) { while (false !== ($file = @readdir($handle))) : if( @preg_match("/\.xml/", $file ) ) : $time = preg_replace("/\.xml/", "", $file ); if ( ( $time + 3600 ) < time() ) : unlink( $file ); endif; endif; endwhile; closedir($handle); } ?> PHP: Like that ...... however, I agree that the time isnt a great schema to use, you should use a mixture of maybe time and sessionid time_phpsessionid.xml would work, then you can still split the filename to get the time it was created ....
Forget trying to do this in php when there are much easier ways to do it . A cron job is the best approach to doing a task like this - I do it all the time 23 * * * * rm -f `find /dir/to/files/ -cmin +60` > /dev/null 2>&1 The above cron job will run at 23 mins past each hour and look in the /dir/to/files/ directory for all files that were created longer than 60 minutes ago. The rm -f ` ` will remove all files that are found as a result of running the command. Of course, you will need to ensure that the file ownership is such that you can delete them.