Skip to main content

PHP: Recursively Delete Old Files

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

Published 1 min readMarkdown
Part of seriesCodeTalk
PHP: Recursively Delete Old Files

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.

192 views

About the author

  • I work with Linux in the day, ballroom dancing at night. I use Arch, btw.

No comments yet. Be the first to comment.

CodeTalk

Part 4 of 5

In this series, I will share code that is useful for solving problems. Talk code and dream code.

Up nextScript For Converting To/From UNIX TimePHP Command Line Script

More from this blog