Monday 25 July 2016

Remove Files Older than a date in PHP

PHP function to remove files older than number of days. This simple function takes directory path and no of days as arguments and removes the files older than particular days from the directory.

function removeFilesOlderThan($dir_path, $$no_of_days) {
    if ($handle = opendir($dir_path)) {
        while (false !== ($file = readdir($handle))) {
            $filelastmodified = filemtime($dir_path . '/' . $file);
            $filetype = filetype($dir . '/' . $file);
            if($filetype != 'file') continue;
            if((time() - $filelastmodified) > 24*60*60*$$no_of_days){
                unlink($dir_path . '/' . $file);
            }
        }
        closedir($handle);
    }
    else {
        echo "Directory not available";
    }
}


Make use of the function to remove backup files automatically after particular days in order to avoid too much of load in the server.

No comments:

Post a Comment