Created
December 22, 2019 17:52
-
-
Save mtvbrianking/469b5060d5dbf48146ad470bc30e81f6 to your computer and use it in GitHub Desktop.
Delete files older than a certain date.
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
<?php | |
/** | |
* Delete files older than a given age recursively. | |
* | |
* @link https://www.php.net/manual/en/class.recursivedirectoryiterator.php#111142 Source | |
* | |
* @param string $dir Path to directory having the files | |
* @param int $age In seconds | |
* @param string $pattern File name pattern | |
* | |
* @throws UnexpectedValueException | |
* | |
* @return array Deleted files | |
*/ | |
function deleteExpiredFiles($dir, $age, $pattern = null) | |
{ | |
$rdi = new \RecursiveDirectoryIterator($dir); | |
// $rii = new \RecursiveIteratorIterator($rdi); | |
$rii = new \RecursiveIteratorIterator($rdi, \RecursiveIteratorIterator::CHILD_FIRST); | |
$deleted = []; | |
$limit = time() - $age; | |
foreach ($rii as $splFileInfo) { | |
$fileName = $splFileInfo->getFilename(); | |
// Skip hidden files and directories. | |
if ($fileName[0] === '.') { | |
continue; | |
} | |
if($pattern && !preg_match($pattern, $fileName)) { | |
continue; | |
} | |
if ($splFileInfo->getMTime() > $limit) { | |
continue; | |
} | |
$path = $splFileInfo->isDir() | |
? array($fileName => []) | |
: array($fileName); | |
for ($depth = $rii->getDepth() - 1; $depth >= 0; $depth--) { | |
$path = array($rii->getSubIterator($depth)->current()->getFilename() => $path); | |
} | |
$deleted = array_merge_recursive($deleted, $path); | |
if($splFileInfo->isDir()) { | |
// rmdir($splFileInfo->getRealPath()); | |
continue; | |
} | |
unlink($splFileInfo->getRealPath()); | |
} | |
return $deleted; | |
} | |
// $dir = storage_path('backups'); | |
$dir = "C:\\xampp\\htdocs\\integrations\\storage\\backups"; | |
$age = 3600*24*7; | |
$pattern = "/^(.*?)(.json)$/"; | |
$deleted = deleteExpiredFiles($dir, $age, $pattern); | |
echo json_encode($deleted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment