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

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

Just curious

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


        
9条回答
  •  攒了一身酷
    2020-12-05 02:10

    You should add an is_file() check, because PHP normally lists . and .., as well as sub-directories that 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.

    = 60 * 60 * 24 * 2) { // 2 days
            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.

提交回复
热议问题