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

后端 未结 9 2375
一生所求
一生所求 2020-12-05 01:56

Just curious

        $files = glob(cacheme_directory().\"*\");
        foreach($files as $file)
        {
            $filemtime=filemtime ($file);
                  


        
9条回答
  •  渐次进展
    2020-12-05 02:10

    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
    ".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

提交回复
热议问题