PHP: Recursively Delete Old Files

Photo by Devin Avery on Unsplash

PHP: Recursively Delete Old Files

Useful for purging backup/temporary/cache files after a certain period of time.

·

1 min read

I have a folder named "storage". There are log files and temporary cache files created within hierarchy of subfolders. I need to traverse through all subfolders and delete files older than 6 months (based on modified time).

$timeThreshold = strtotime("-6 months");

Files last modified before this timestamp will be deleted.

$iterator = new RecursiveDirectoryIterator($folder);

Using RecursiveDirectoryIterator for recursive folder traversal. listDeletableFiles function can be customize to filter files for deletion. For example, you may want to delete files with ".log" extension.