Created
March 8, 2023 09:43
-
-
Save pepijnolivier/d6b4deda0a7634b01bd0bc887c89203c to your computer and use it in GitHub Desktop.
PHP: Recursively delete old files and folder in a given directory
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
/** | |
* @param $folderName | The full directory name | |
* @param $maxAge | Max Age in seconds. 172800 = 2 days. | |
*/ | |
private function recursivelyPruneDirectory($folderName, $maxAge = 60) | |
{ | |
$items = array_diff(scandir($folderName), ['.','..']); | |
foreach ($items as $fileOrFolder) { | |
$path = "$folderName/$fileOrFolder"; | |
$startsWithDot = str_starts_with($fileOrFolder, '.'); | |
if ($startsWithDot) { | |
continue; | |
} | |
$isTooOld = time() - filemtime($path) >= $maxAge; | |
if (!$isTooOld) { | |
continue; | |
} | |
if (is_file($path)) { | |
unlink($path); | |
} elseif (is_dir($path)) { | |
// Do not dive into symbolic links... | |
if (is_link($path)) { | |
continue; | |
} | |
// first recursively prune this underlying directory then | |
$this->recursivelyPruneDirectory($path, $maxAge); | |
// now check if it is empty. If so, delete it! | |
$subItems = array_diff(scandir($path), ['.','..']); | |
if (empty($subItems)) { | |
rmdir($path); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment