phpfilecaching

The correct way to delete all files older than 2 days in PHP


Just curious:

$files = glob(cacheme_directory() . '*');
foreach ($files as $file) {
    $filemtime = filemtime($file);
    if (time() - $filemtime >= 172800) {
        unlink($file);
    }
}

I just want to make sure if the code is correct or not. Thanks.


Solution

  • You should add an is_file() check, because sub-directories could reside in the the directory you're checking.

    Also, as this answer suggests, you should replace the pre-calculated seconds with a more expressive notation.

    $files = glob(cacheme_directory() . '*');
    $threshold = strtotime('-2 day');
      
    foreach ($files as $file) {
        if (is_file($file)) {
            if ($threshold >= filemtime($file)) {
                unlink($file);
            }
        }
    }
    

    Alternatively you could also use the DirectoryIterator, as shown in this answer. In this simple case it doesn't really offer any advantages, but it would be OOP way.