Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Created December 22, 2019 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/469b5060d5dbf48146ad470bc30e81f6 to your computer and use it in GitHub Desktop.
Save mtvbrianking/469b5060d5dbf48146ad470bc30e81f6 to your computer and use it in GitHub Desktop.
Delete files older than a certain date.
<?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