Question

I have a folder that has files with names

2014-01-28_backup.txt
2014-01-25_backup.txt
2014-01-26_backup.txt
2014-01-27_backup.txt

I want to create a script that deletes 3 days old file, so If I run the script on 2014-01-29, It should delete all the files prior to 26. I have seen a function called glob and scandir but not sure how to get that in

Was it helpful?

Solution

Try this,

$threeDbefore = date("Y-m-d", strtotime("-3 days"));
foreach(glob("path/to/files/*") as $file) {
    if (!is_file($file)) {
        continue;
    }
    $fileParts = explode('_', basename($file));
    if(!empty($fileParts[0]) && $fileParts[0] <= $threeDbefore) {
        unlink($file);
    }
}

This will also delete files before 3 days, not just exactly 3 days. i.e it will delete '2014-01-24_backup.txt and 2014-01-23_backup.txt etc

OTHER TIPS

Of course your folder and files must have write permission ( chmod 777 )

foreach (glob("path/to/files/*") as $file) {
    if(substr(basename($file), 0, 10) <= date("Y-m-d",strtotime("-3 days"))) 
    unlink($file);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top