The correct way to delete all files older than 2 d

2019-01-14 05:38发布

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.

标签: php file caching
8条回答
何必那么认真
2楼-- · 2019-01-14 06:32

Here is an example of how to do it recursively.

function remove_files_from_dir_older_than_x_seconds($dir,$seconds = 3600) {
    $files = glob(rtrim($dir, '/')."/*");
    $now   = time();
    foreach ($files as $file) {
        if (is_file($file)) {
            if ($now - filemtime($file) >= $seconds) {
                echo "removed $file<br>".PHP_EOL;
                unlink($file);
            }
        } else {
            remove_files_from_dir_older_than_x_seconds($file,$seconds);
        }
    }
}

remove_files_from_dir_older_than_x_seconds(dirname(__file__).'/cache/', (60 * 60 * 24 * 1) ); // 1 day
查看更多
再贱就再见
3楼-- · 2019-01-14 06:33

Be aware that you'll run into problems if you have a very large number of files in the directory.

If you think this is likely to affect you, consider using a lower level approach such as opendir.

查看更多
登录 后发表回答