I have a index.php script that runs every night to backup a mySQL database (through CRON) on my website. The script store the file in the folder where the script is. I wanted to created another script that would delete backup files older than 7 days. So I used this one from tdebatty on GitHub:
<?php
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 = "[email protected]";
// 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);
The script works well, but I would like to limit deletion to files starting with "XXX’ or .sql.gz files. In the backup folder i have all the .sql.gz backup alongside the index.php script that is used daily to backup. This index.php file is not modified as the days go by, so it gets older and it is deleted by the deletion script at some point.
Thank you !
I tried to modify existing if conditions: if (!is_file($file) || strpos($file, "XXX") !== 0) {
or if (filemtime($file) < $limit && strpos($file, "XXX") === false) {
or if (pathinfo($file, PATHINFO_EXTENSION) == 'sql.gz' && filemtime($file) < $limit) {
I also tried to add another if condition in the loop:
if (strpos($file, "XXX") !== 0) {
continue;
}
None of these works and I don’t understand why. Script doesn’t work anymore, nothin happens. Any clue? Sorry if it’s obvious, I’m still learning 🙂
3
Answers
An acquaintance found the issue: when targeting by extension type, in my case file extension is "gz", not "sql.gz".
Have you tried str_contains()?
str_contains(string $haystack, string $needle): bool
Here your mistake, the script redefine
$file
with this$file = $dir . '/' . $file;
and you create a conditionstrpos($file, "XXX") !== 0
, so your condition will like thisstrpos("/YOURPATH/XXX", "XXX") !== 0
Also you create this condition
pathinfo($file, PATHINFO_EXTENSION) == 'sql.gz'
is wrong because output ofpathinfo($file, PATHINFO_EXTENSION)
is only extension (gz
,txt
,etc)Here the working code
For testing, use this code for generate a random file.
Then use it
Here live code test : https://onlinephp.io/c/3fc02