<?php
    
/*
        filename : backup-mysql.php
        short description : mysql backup utility
        desciption : Backup all databases of a specified user.
                     All databases are stored in separate files.
                     Store database of the $intNbPastDay past days.
                     Store database of all day of a month specified in $arrDayOfMonth.
        usage : Add 'php /home/phpcli/backup-mysql.php' to your daily cron jobs.
        author : BenoĆ®t RAUX -> http://twitter.com/rauxbenoit
        revision : 2010-02-04
    */
    
    // CONFIG VARS
    
$strMysqlServer    'localhost';
    
$strMysqlUser    'user';
    
$strMysqlPass    'pass';
    
$strBackupDir    '/data/backup/mysql/';
    
$arrDayOfMonth    = array('01','15');
    
$intNbPastDay    14;
    
    
// DISPLAY AND EXEC A SHELL COMMAND
    
function my_shell_exec($str){
        echo 
$str "\n";
        echo 
shell_exec($str) . "\n";
    }
    
    
// LIST DATABASES AND EXEC A 'mysqldump' AND A bzip2 ON IT
    
$argMysql mysql_connect($strMysqlServer,$strMysqlUser,$strMysqlPass);
    if (!
$argMysql) {
        die(
'Warning could not connect to mysql : ' mysql_error());
    } else {
        
$reqListDb 'SHOW DATABASES;';
        
$recListDb mysql_query($reqListDb) or die(mysql_error());
        while(
$objDb mysql_fetch_object($recListDb)){
            
$strDb $objDb->Database;
            
$strDbBkp $strDb '-' date('Ymdhis') . '.sql.bz2';
            
$strCmd 'mysqldump ';
            
$strCmd.= '-h' escapeshellcmd($strMysqlServer) . ' ';
            
$strCmd.= '-u' escapeshellcmd($strMysqlUser)  . ' ';
            
$strCmd.= '-p' escapeshellcmd($strMysqlPass)  . ' ';
            
$strCmd.= escapeshellcmd($strDb) . ' ';
            
$strCmd.= '| bzip2 > ';
            
$strCmd.= $strBackupDir;
            
$strCmd.= $strDbBkp;
            
my_shell_exec($strCmd);
        }
        
mysql_close($argMysql);
    }

    
// LIST ALL DATABASES FILES IN BACKUP DIRECTORY, AND PARSE THIS LIST
    
$intTimeRef strtotime(date('Ymd'));
    
$arrDbFile  glob($strBackupDir '*.sql.bz2');
    foreach(
$arrDbFile as $strDbFile){
        
// EXTRACT FILE'S DATE
        
$strDbFileName basename($strDbFile,'.sql.bz2');
        
$strDbFileDate substr($strDbFileName,(strrpos($strDbFileName,'-')+1),8);
        
$intDbFileTime strtotime($strDbFileDate);
        
// TEST DATE MATCH STORAGE RULES
        
$booDel true;
        
// IN $intNbPastDay PAST DAYS ?
        
if(($intTimeRef $intDbFileTime)<=($intNbPastDay 60 60 24)){
            
$booDel false;
        }
        
// SPECIFIED IN  $arrDayOfMonth ?
        
if($booDel == true){
            if(
in_array(date('d',$intDbFileTime),array('01','15'))){
                
$booDel false;
            }    
        }
        
// DELETE ?
        
if($booDel == true){
            
$strCmd 'rm -f ' $strDbFile;
            
my_shell_exec($strCmd);
        }
    }

?>