Code to recursively delete files and folder older than x days

To make a more free space in the web server, it is better if we delete the unnecessary files and folders. Cleaning-up unnecessary files and folder, time and again, manually is a tedious job.

The PHP has RecursiveDirectoryIterator class that provides an interface for iterating recursively over filesystem directories .  And the another class, the RecursiveIteratorIterator is used to iterate through the recursive iterators.

Using these two classes, we can quickly find all the files and folder (recursively) in a certain directory.

Let’s write PHP script that delete unused files and folder one by one older than given number of days.

The following code iterates recursively inside the image folder to get all the files and folders and delete the file and folder older than 5 days .

We can change the directory name and number of days and  add the aforementioned PHP script in a CRON or run the script manually.

To delete all the files and folders inside the directory,  remove if condition that compares the current time with the time when the file/folder was created.

The code to delete recursive files and folders is specially useful, when the files and folder inside the certain directory gets frequently updated.



Hits: 200


2 thoughts on “Code to recursively delete files and folder older than x days

Comments are closed.