Skip to content

Instantly share code, notes, and snippets.

@craiga
Created July 23, 2012 00:49
Show Gist options
  • Save craiga/3161529 to your computer and use it in GitHub Desktop.
Save craiga/3161529 to your computer and use it in GitHub Desktop.
removeOldFiles
<?php
/**
* Remove old files.
*
* Remove files older than one day (or the age specified). Will not remove old directories.
*
* @param $directory The directory to remove files from.
* @param $recursive Whether to remove files from subdirectories as well. False by default.
* @param $age The minimum age of a file before it is removed. One day by default.
* If there isn't enough free space available, this may be overridden.
* @param $freeSpace Minimum amount of free space there should be remaining after removing old files. 0 by default.
* If there is less than this amount of free space, the function will be called again with the age halved.
* Treated as a percentage if < 1 (i.e. 0.1 = 10% of disk should be free), treated as number of bytes if 1 or greater (i.e. 2000 = 2000 bytes should be free).
* @param $removeEmptyDirs Whether to remove empty directories, regardless of age. False by default.
*
* @author Craig Anderson <[email protected]>
* @link https://gist.github.com/craiga/3161529
*/
function removeOldFiles($directory, $recursive = false, $age = 86400, $freeSpace = 0, $removeEmptyDirs = false)
{
if (!is_readable($directory)) {
throw new RuntimeException("Can't read directory " . $directory);
}
$files = scandir($directory);
if (!$files) {
throw new RuntimeException("Couldn't get list of files in directory " . $directory);
}
foreach ($files as $file) {
// Skip "." and ".."
if ($file == "." || $file == "..") {
continue;
}
$realfile = realpath($directory . DIRECTORY_SEPARATOR . $file);
if (is_dir($realfile)) {
if ($recursive) {
removeOldFiles($realfile, $recursive, $age, $removeEmptyDirs); // Don't include freeSpace argument! We should only check if enough free space is available after all recursive calls have been made.
}
if ($removeEmptyDirs && count(array_diff(scandir($realfile), array(".", ".."))) < 1) { // Scandir will return array(".", "..") if the directory is empty
if (!rmdir($realfile)) {
throw new RuntimeException("Couldn't delete empty directory " . $realfile);
}
}
}
if (is_file($realfile)) {
$fileage = time() - filemtime($realfile);
if ($fileage > $age) {
if (!unlink($realfile)) {
throw new RuntimeException("Couldn't delete file " . $realfile);
}
}
}
}
$realFreeSpace = disk_free_space($directory);
if ($freeSpace < 1) {
$realFreeSpace = disk_free_space($directory) / disk_total_space($directory);
}
if ($realFreeSpace < $freeSpace && $age > 2) {
removeOldFiles($directory, $recursive, (int)($age / 2), $removeEmptyDirs, $freeSpace);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment