Skip to content

Delete Files Older than n Number Of days Using PHP?

Some times in application development, we required to delete files older than specified number of days. Actually below method removes older files from disk and free the hard disk memory.

Below example demonstrate how to delete files, older than specified number of days. This code delete files from specified directory only, not from child folders. deleteOldFiles() method takes three parameters first one is folder/directory path, second one is number of days and third parameter is return count.

Simple Method to Delete Files Older than n Number Of days

isDot() || $fileInfo->isDir()) {
			  continue;
			}
			if (time() - $fileInfo->getCTime() > ($days *86400)) {
				unlink($fileInfo->getRealPath());
				if($count) { 
				    $countDeletedFiles++;
				 }
			}
		}
		return $count ? $countDeletedFiles : FALSE;
	}
	return FALSE;
}

echo deleteOldFiles('test');
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments