Search code examples
phpglobunlinkscandir

Deleting 3 days old file from folder in php


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


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