Created
January 29, 2014 16:27
-
-
Save alexandrusavin/8691618 to your computer and use it in GitHub Desktop.
Script to delete lot's of files without a big impact on the system IO
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 | |
// path where the files should be deleted | |
define('PATH', '/.'); | |
// delete only files older than OLDER_THAN_DAYS days | |
define('OLDER_THAN_DAYS', 14); | |
// delete only files that match MATCH_NAME | |
define('MATCH_NAME', '/some regexp/i'); | |
// do NOT actually delete the files | |
define('DRYRUN', false); | |
// sleep SLEEP_USEC microsecconds after each delete | |
define('SLEEP_USEC', 5000); // I have good experience with setting it to 5 milisecs | |
$older_than = time() - OLDER_THAN_DAYS * 24 * 60 * 60; | |
$to_delete = array(); | |
$success = 0; | |
$failed = 0; | |
$count = 0; | |
$echo = ""; | |
$freespace = 0; | |
try { | |
$dir = new DirectoryIterator(PATH); | |
foreach ($dir as $file) { | |
if (!$file->isDot() && $file->isFile() && $file->getMTime() > $older_than | |
&& preg_match(MATCH_NAME, $file->getBasename())) { | |
if (DRYRUN) { | |
$success++; | |
$freespace += $file->getSize(); | |
} else { | |
$size = $file->getSize(); | |
if (@unlink ($file->getPathname())) { | |
$success++; | |
$freespace += $size; | |
} else { | |
$failed++; | |
} | |
usleep(SLEEP_USEC); | |
} | |
$count++; | |
echo "\033[".(strlen($echo))."D"; | |
$echo = "Went through " . $count . " files and deleted $success successfully and $failed unsuccessfully. Made " . round($freespace / 1024 / 1024) . "M of freespace."; | |
echo $echo; | |
} | |
} | |
} catch (UnexpectedValueException $e) { | |
throw new Exception("Directory path wrong [".$e->message."]"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment