Skip to content

Instantly share code, notes, and snippets.

@gaffling
Last active March 24, 2021 07:14
Show Gist options
  • Save gaffling/96609f7ce8c3ab528a39de788ee37b84 to your computer and use it in GitHub Desktop.
Save gaffling/96609f7ce8c3ab528a39de788ee37b84 to your computer and use it in GitHub Desktop.
[Delete Old] Delete files older than a given age (in seconds) #php #function #delete
<?php
/* -------------------------------------------------------------------------------------------- */
/* [Delete Old] Delete files older than a given age (in seconds) recusiv #php #function #delete */
/* -------------------------------------------------------------------------------------------- */
// TEST
delete_older_than('limit', 1);
/**
* delete_older_than()
* delete files older than a given age (in seconds) recusiv
*
* @see https://gist.github.com/tdebatty/9412259
* @see https://www.php.net/manual/de/function.filemtime.php#32728
*
* @param [string] $dir [Path of the Folder that should be purged]
* @param [integer] $max_age_in_seconds [60*3 = 3 Minutes | 60*60*24*7 = 7 Days]
* @param [array] $skip [Array with Filenames that should never be deleted]
*/
function delete_older_than($dir, $max_age_in_seconds, $skip=array()) {
$dir = realpath($dir);
if (is_dir($dir)) {
$limit = time() - $max_age_in_seconds;
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != '.' and $object != '..' and !in_array($object, $skip)) {
if (is_dir($dir.DIRECTORY_SEPARATOR.$object) && !is_link($dir.DIRECTORY_SEPARATOR.$object)) {
delete_older_than($dir.DIRECTORY_SEPARATOR.$object, $max_age_in_seconds);
} else {
if (filemtime($dir.DIRECTORY_SEPARATOR.$object) < $limit) {
unlink($dir.DIRECTORY_SEPARATOR.$object);
}
}
}
}
if (filemtime($dir.DIRECTORY_SEPARATOR.'.') < $limit) {
rmdir($dir);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment