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

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

Just curious

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


        
9条回答
  •  不知归路
    2020-12-05 02:11

    Another simplier and more modern way, using FilesystemIterator.

    I'm using 'logs' directory as an example.

    $fileSystemIterator = new FilesystemIterator('logs');
    $now = time();
    foreach ($fileSystemIterator as $file) {
        if ($now - $file->getCTime() >= 60 * 60 * 24 * 2) // 2 days 
            unlink('logs/'.$file->getFilename());
    }
    

    Main advantage is: DirectoryIterator returns virtual directories "." and ".." in a loop. But FilesystemIterator ignores them.

提交回复
热议问题