Last active
July 13, 2021 00:59
-
-
Save jpneey/a76c06cbaf577da7edbc23640009c319 to your computer and use it in GitHub Desktop.
Delete images that is older than 30 days
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 | |
header("Content-type: application/json"); | |
$now = new DateTime(); | |
$cleaned = $purged = $saved = 0; | |
$files = glob("./file/directory/that/holds/items/*.{jpg,png,gif,JPG,jpeg}", GLOB_BRACE); | |
for ($i = 0; $i < count($files); $i++){ | |
$date = date('Y-m-d h:i:s', filemtime($files[$i])); | |
$dateToTest = new DateTime($date); | |
if ($dateToTest->diff($now)->days > 30) { | |
unlink($files[$i]); | |
$cleaned++; | |
$purged += filesize($files[$i]); | |
clearstatcache(); | |
} | |
} | |
if ($cleaned) { | |
$byte = floor(log($purged) / log(1024)); | |
$sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); | |
$saved = sprintf('%.02F', $purged / pow(1024, $byte)) * 1 . ' ' . $sizes[$byte]; | |
} | |
$response = array( | |
"Total image deleted" => $cleaned, | |
"Total space saved" => $saved | |
); | |
echo json_encode($response); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment