Skip to content

Instantly share code, notes, and snippets.

@hongster
Last active October 18, 2022 03:20
Show Gist options
  • Save hongster/6eacdbb4c08a8efe0a1aac720d662c6d to your computer and use it in GitHub Desktop.
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.
#!/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