Quantcast
Viewing all articles
Browse latest Browse all 6

PHP: Deleting all files from a folder that reached a certain age (x hours/days/weeks/months/years)

Here a quick example that explains how to delete all files of a folder that are older the x days/minutes/hours/months. This method works under both windows and unix. The custom getCorrectMTime() function was posted on the PHP documentation and takes into account that time measurement under windows and unix is slightly different. Of course I also have a small ignore list where files (eg .htaccess, index.html etc) can be blocked from getting deleted.

/**
     * @param $folder the folder in which the old files are supposed to get purged
     * @param $maximumAge maximum file age in seconds
     * @param $ignoreList array() of filenames that should get ignored
     */
    public function deleteOldFiles($folder, $maximumAge,$ignoreList){
        $dir=scandir($folder);
        foreach($dir as $file){
            $secretFileTime=$this->getCorrectMTime($folder.$file);
            $fileAge=time()-$secretFileTime;
            if(($file!='..')&&($file!='.')&&($file!='index.html')&&(!in_array($file,$ignoreList))){
                if($fileAge>$maximumAge){
                    unlink($folder.'/'.$file);
                    //echo "
deleting ".$folder.$file." because it has the age: ".$fileAge;
                }else{
                    //echo "
keeping ".$folder.$file." because it has the age: ".$fileAge;
                }
            }else{
                //echo "
ignored ".$file;
            }
        }
    }
 
public function getCorrectMTime($filePath){
 
        $time = filemtime($filePath);
 
        $isDST = (date('I', $time) == 1);
        $systemDST = (date('I') == 1);
 
        $adjustment = 0;
 
        if($isDST == false && $systemDST == true)
            $adjustment = 3600;
 
        else if($isDST == true && $systemDST == false)
            $adjustment = -3600;
 
        else
            $adjustment = 0;
 
        return ($time + $adjustment);
    }

Der Beitrag PHP: Deleting all files from a folder that reached a certain age (x hours/days/weeks/months/years) erschien zuerst auf notboring dev blog.


Viewing all articles
Browse latest Browse all 6

Trending Articles