Remove Files Older than Number of Days

by Sasikumar 2014-07-16 10:39:27

We can use the following function to remove files older than particular number of days.
This function needs two parameters namely "Directory path" and "Number of Days". This function compares the last modified date and process on its basis.

PHP Function :
function remove_files_older_than($dir, $days)
{
    if ($handle = opendir($dir)) {
        while (false !== ($file = readdir($handle))) {
            $filelastmodified = filemtime($dir . '/' . $file);
            $filetype = filetype($dir . '/' . $file);
            if($filetype != 'file') continue;
            if((time() - $filelastmodified) > 24*60*60*$days){
                unlink($dir . '/' . $file);
            }
        }
        closedir($handle);
    }
}
Example Usage :
remove_files_older_than("path/to/remove/dir", 5);
1032
like
0
dislike
0
mail
flag

You must LOGIN to add comments