Last active
December 22, 2019 08:14
-
-
Save mtvbrianking/90f19705a38b27ee33f13ca7e4c3842c to your computer and use it in GitHub Desktop.
Delete files older than a certain date.
This file contains hidden or 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. | |
* | |
* @param string $dirPath Path to directory having the files | |
* @param int $maxAge In seconds | |
* @param string $pattern File name pattern | |
* | |
* @return array Deleted files | |
*/ | |
function deleteExpiredFiles($dirPath, $maxAge, $pattern = null) { | |
$deleted = []; | |
$limit = time() - $maxAge; | |
$dirPath = realpath($dirPath); | |
if (!is_dir($dirPath)) { | |
return; | |
} | |
$dh = opendir($dirPath); | |
if ($dh === false) { | |
return; | |
} | |
while (($fileName = readdir($dh)) !== false) { | |
$filePath = $dirPath . '/' . $fileName; | |
if (!is_file($filePath)) { | |
continue; | |
} | |
if($pattern && !preg_match($pattern, $fileName)) { | |
continue; | |
} | |
if (filemtime($filePath) < $limit) { | |
$deleted[] = $fileName; | |
unlink($filePath); | |
} | |
} | |
closedir($dh); | |
return $deleted; | |
} | |
$logDir = storage_path('logs'); | |
$sevenDays = 3600*24*7; | |
$logPattern = "/^(laravel)(.*?)(.log)$/"; | |
$deleted = deleteExpiredFiles($logDir, $sevenDays, $logPattern); | |
echo "Deleted " . count($deleted) . " files:\n-> " . implode("\n-> ", $deleted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment