How to delete files from directory based on creation date in php?

前端 未结 8 1786
囚心锁ツ
囚心锁ツ 2020-11-29 03:52

I have a cache folder that stores html files. They are overwritten when needed, but a lot of the time, rarely used pages are cached in there also, that just end up using sp

8条回答
  •  醉梦人生
    2020-11-29 04:42

    Try SplIterators

    // setup timezone and get timestamp for yesterday
    date_default_timezone_set('Europe/Berlin'); // change to yours
    $yesterday = strtotime('-1 day', time());
    
    // setup path to cache dir and initialize iterator
    $path      = realpath('/path/to/files'); // change to yours
    $objects   = new RecursiveIteratorIterator(
                     new RecursiveDirectoryIterator($path));
    
    // iterate over files in directory and delete them
    foreach($objects as $name => $object){
        if ($object->isFile() && ($object->getCTime() < $yesterday)) {
            // unlink($object);
            echo PHP_EOL, 'deleted ' . $object;
        }
    }
    

    Creation Time is only available on Windows.

提交回复
热议问题