Skip to content

Instantly share code, notes, and snippets.

@hongster
Created Aug 25, 2022
Embed
What would you like to do?
#!/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