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 .
$dir = 'images/'; $now = time(); $dir = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS); $dir = new \RecursiveIteratorIterator($dir,\RecursiveIteratorIterator::CHILD_FIRST); $deleteFiles =[]; $message = "There is no file to delete"; if($dir) { foreach ($dir as $file) { /* Comparing the current time with the time when file was created */ if ($file && $now - filemtime($file) >= 60 * 60 * 24 * 5) { // 5 days array_push($deleteFiles, $file); $file->isDir() ? rmdir($file) : unlink($file); $message = "All the following files are deleted.<br/>"; } } }else { } echo $message; if($deleteFiles){ var_dump(implode('<br/>',$deleteFiles)); }
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.
$imageFolder = 'images/'; $now = time(); $dir = $imageFolder; $dir = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS); $dir = new \RecursiveIteratorIterator($dir,\RecursiveIteratorIterator::CHILD_FIRST); $deleteFiles =[]; $message = "There is no file to delete"; if($dir) { foreach ($dir as $file) { array_push($deleteFiles, $file); $file->isDir() ? rmdir($file) : unlink($file); $message = "All the following files are deleted.<br/>"; } } echo $message; if($deleteFiles){ var_dump(implode('<br/>',$deleteFiles)); }
The code to delete recursive files and folders is specially useful, when the files and folder inside the certain directory gets frequently updated.
Views: 695
A journey begins with a small step. Keep Going! Kudos
Thanks