Skip to main content

Command Palette

Search for a command to run...

PHP: Recursively Delete Old Files

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

Published
1 min read
PHP: Recursively Delete Old Files
H

I am a developer from Malaysia. I work with PHP most of the time, recently I fell in love with Go. When I am not working, I will be ballroom dancing :-)

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.

191 views

CodeTalk

Part 4 of 5

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

Up next

Script For Converting To/From UNIX Time

PHP Command Line Script

More from this blog

Hong's Tech Blog

110 posts

The blog is older than you know. I prefer counting from the emergence of one integral anomaly to the emergence of the next, in which case this is the forth version.