Skip to content

Instantly share code, notes, and snippets.

@tdebatty
Last active November 15, 2023 07:23
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save tdebatty/9412259 to your computer and use it in GitHub Desktop.
Save tdebatty/9412259 to your computer and use it in GitHub Desktop.
A simple PHP function to delete files older than a given age. Very handy to rotate backup or log files, for example...
<?php
/**
* A simple function that uses mtime to delete files older than a given age (in seconds)
* Very handy to rotate backup or log files, for example...
*
* $dir String whhere the files are
* $max_age Int in seconds
* return String[] the list of deleted files
*/
function delete_older_than($dir, $max_age) {
$list = array();
$limit = time() - $max_age;
$dir = realpath($dir);
if (!is_dir($dir)) {
return;
}
$dh = opendir($dir);
if ($dh === false) {
return;
}
while (($file = readdir($dh)) !== false) {
$file = $dir . '/' . $file;
if (!is_file($file)) {
continue;
}
if (filemtime($file) < $limit) {
$list[] = $file;
unlink($file);
}
}
closedir($dh);
return $list;
}
// An example of how to use:
$dir = "/my/backups";
$to = "my@email.com";
// Delete backups older than 7 days
$deleted = delete_older_than($dir, 3600*24*7);
$txt = "Deleted " . count($deleted) . " old backup(s):\n" .
implode("\n", $deleted);
mail($to, "Backups cleanup", $txt);
@kaleem7832
Copy link

Thank you for this script. its works like charm.

@nickschnee
Copy link

this is great, thank you very much.

@pwiking
Copy link

pwiking commented Mar 28, 2020

Looks great.
Is it deleting the files in subdirectories too?
Thx

@alil0rd
Copy link

alil0rd commented May 9, 2020

How can I delete specific extension files?

@ramirezcoronel
Copy link

It worked flawlessly, thanks!

@hussnainsheikh
Copy link

hussnainsheikh commented Sep 5, 2021

Looks great.
Is it deleting the files in subdirectories too?
Thx

Please find this fork, I have updated the script to remove the files in the subdirectories. Thank you!

@adrianohcampos
Copy link

thanks!

@masikhsanms
Copy link

thanks work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment