We require a way to remove old db files from the storage|backups folder and I was wondering if there is a way to do this automatically or if someone has written a plugin that does it via a cron job?
******* Updated based on khalwat's comment ************
I don't think Craft does that automatically. Not sure about 3rd party plugins.
I wrote a custom controller function to run by Cron Job, and it's been working fine.
It does nothing but looping through the .sql files in the craft/storage/backups folder and delete the ones which are older than X days, based on the modified time of the file.
public function actionDeleteOldBackups() {
try {
$dir = 'craft/storage/backups';
$backupFiles = scandir($dir);
$x = craft()->config->get('xDaysToDeleteDbBackup') ?: 30; // Keep the backup files for 30 days by default. Change it to w/e you like.
// Craft uses Greenwitch time to name the backup files
$xDaysAgo = strtotime('-' . $x . ' days', time());
// depending on how you want to compare the dates, the following line can be ignored.
$xDaysAgo = strtotime(date('y-m-d', $xDaysAgo));
// loop through files, find the file's last modified time and compare with $xDaysAgo
if(!empty($backupFiles)) {
foreach ($backupFiles as $fileName) {
if(strpos($fileName, '.sql') !== false) {
$filepath = $dir . '/' . $fileName;
if(file_exists($filepath)) {
$created = filemtime($filepath);
if($created && $created < $xDaysAgo) {
// print_r($filepath . ' '); // for testing
unlink($filepath); //delete the file
}
}
}
}
}
\Yii::app()->end(); // no render
} catch (\Exception $e) {
die('Failed to delete dated backup files.');
}
}
Put the function in one of the controller of your custom plugin, kindly reminder to allow anonymous access for this function. The URL for the Cron Job will be something like:
[host]/actions/pluginhandle/deleteOldBackups
-
1You could do it a lot easier by just looking at the
mtime
of the file. Example here: github.com/nystudio107/craft-scripts/blob/master/scripts/… – andrew.welch Sep 4 '17 at 14:52 -