-
-
Save hongster/6eacdbb4c08a8efe0a1aac720d662c6d to your computer and use it in GitHub Desktop.
Recursively delete files older than certain time. Useful for automating clearing log/cache/temporary files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
/** | |
* Entry point of this application. | |
*/ | |
function main() { | |
$folder = "/tmp/storage"; | |
$timeThreshold = strtotime("-6 months"); | |
$deletableFile = listDeletableFiles($folder, $timeThreshold); | |
foreach ($deletableFile as $file) { | |
unlink($file); | |
} | |
} | |
/** | |
* Recursively traverse within `$folder`, list files older than `$timeThreshold` (based on modified time). | |
* | |
* @param string $folder Folder path. | |
* @param int $timeThreshold UNIX timestamp. | |
* @return array List of file paths in string. | |
*/ | |
function listDeletableFiles($folder, $timeThreshold) { | |
$filteredFiles = []; | |
$iterator = new RecursiveDirectoryIterator($folder); | |
foreach(new RecursiveIteratorIterator($iterator) as $file) { | |
if (substr($file->getFilename(), 0, 1) == '.') { // Skip hidden files | |
continue; | |
} | |
elseif ($file->getMTime() < $timeThreshold) { | |
$filteredFiles[] = $file->getPathname(); | |
} | |
} | |
return $filteredFiles; | |
} | |
if (php_sapi_name() == "cli") { | |
main(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment