1

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?

1

******* 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.