Search code examples
phpsecuritycrontemporary-files

PHP: A good script to clear temporary file for cron?


I have a temporary folder generated by my business application and wish for the documents within to be only available for around 30 minutes. I was tempted to build an index to keep track of when each file was created but that would be a little silly for just temporary files, they are not of too much importance but I would like them to removed according to the time they were last modified.

What would I need to do this with my Linux server?


Solution

  • The function filemtime() will allow you to check the last modify date of a file. What you will need to do is run your cron job each minute and check if it is greater than the threshold and unlink() it as needed.

    $time = 30; //in minutes, time until file deletion threshold
    foreach (glob("app/temp/*.tmp") as $filename) {
        if (file_exists($filename)) {
            if(time() - filemtime($filename) > $time * 60) {
                unlink($filename);
            }
        }
    }  
    

    This should be the most efficient method as you requested, change the cron threshold to 10 minutes if you need a less accuracy in case there are many files.