Skip to main content

DATABASE DUMP SCRIPT

<?php

$db_name = 'bountycorporate';

/*
 *
 *  Truncate Watchdog before backup
 *
 */
 
 $con = mysql_connect($db_host, $db_user, $db_pass) or die("");
 if($con){
    mysql_select_db($db_name);
    mysql_query("TRUNCATE TABLE `watchdog`");
    mysql_close($con);
 }

$dump_dir = '/home/backups';

/*
 * First make new backup.
 */

$datetime = date('Y-m-d\TH-i-s');
$dump_file = sprintf('%s/bountycorporate-%s.sql', $dump_dir, $datetime);

$dump_cmd = sprintf(
  'mysqldump -h%s -u%s -p%s %s > %s',
  $db_host, $db_user, $db_pass, $db_name, $dump_file
);
#print $dump_cmd . "\n";
exec($dump_cmd);

$gzip_cmd = sprintf('gzip %s', $dump_file);
#print $gzip_cmd . "\n";
exec($gzip_cmd);

/*
 * Second delete backups older than a week.
 */

$expire_timestamp = strtotime('now - 1 week');
if ($dh = opendir($dump_dir)) {
  while ($file = readdir($dh)) {
    if (preg_match('#^bountycorporate-(\d{4}-\d{2}-\d{2})#', $file, $matches)) {
      $file_timestamp = strtotime($matches[1]);
      if ($file_timestamp < $expire_timestamp) {
        $del_cmd = sprintf('rm %s/%s', $dump_dir, $file);
        #print $del_cmd . "\n";
        exec($del_cmd);
      }
    }
  }
}