Wednesday, January 23, 2013

I wrote a utility to evaluate and remove old backup files...

I finally got around to writing a php script that evaluates the backup directory, removing files older than 3- days.  The script is automatically called by adding the file to the cron.php page.  With the reviewing and removal of older backup files now in place, I felt safe to increase the backups to nightly.

The batch file that generates the .sql files contains this command:

C:\wamp\bin\mysql\mysql5.5.24\bin\mysqldump -u user-ppassword --result-file="drive:\folder\filename.%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2%.sql" dbname
  
I changed the frequency the backup.bat file is called by editing the scheduled task.  I brought up the command window and typed in AT, to view my current job(s).  Then typed AT /delete, removing the current task and then typed in this command to reschedule. At editor help page

  AT 23:59 /EVERY:m,t,w,th,f,s,su drive:\folder\subfolder\dbbackup.bat


I added a require directive to the bottom of the admin/cron.php file. I should add some logic so it is not executed every time the cron scrip runs.

// added by jmergenthaler to remove backup files that are more than 30 days old
// 1/23/13
require('../path/filename.php');

Contents of the script file.

listDirectory();

 function listDirectory(){
    if ($handle = opendir('drive:/folder')) {
        while (false !== ($entry = readdir($handle))) {
            evaluateFile($entry);
        }
        closedir($handle);
    }
}

 function evaluateFile($f){
    //add path to the file
    $file = 'drive:/folder/'.$f;
   
    $fileUnixTimeDate = filemtime($file);
    $todayUnixTimeDate =  time();

    $unixDifference = $todayUnixTimeDate - $fileUnixTimeDate;
   
    $days = round($unixDifference/86400,0);//86400 seconds in a day
       
    if( $days > 30){ //check if the file is older than 30 days

        unlink($file); //delete   
    }
}


This script was not trivial to create.  I used my favorite mentor stackoverflow to help by posting this question on behalf of the script.

Moral of the story?

Use mysqldump to generate frequent backups of your DBs.  Create a .Bat file to execute the mysqldump command on your DBs.  Use AT command (for Windows) to automate the execution of the .BAT file.  Store the backup files in a consistent location on a drive separate from the application files.  Write a script that evaluates the backup directory and removed files based on some rule that works for you.

This is just smart.

1 comment: