Copyright © 2008 - 2012 BestSites.ro Team; Partners: websites-development.com
BestSites.ro » Scripts » Automatic Backups for Database and Files
29.05.10

Automatic Backups for Database and Files

1. Mysql Backup Script
This makes a daily gzip archive with current mysql databases and removes any backup older then 7 days so that you’ll have last 7 backups all the time.
I recommend to run this every day with crontab
0 12 * * * /bin/sh “/home/backups/mysql.sh”

# mysql.sh
mysql_user = user
mysql_pass = 'password'
bk_path	   = '/home/backups/dumps/'
right_now  = `date +"%Y%m%d-h%H"`
bk_fname   = "${bk_path}/dump.sql"
bk_gzname  = "${bk_path}/dump-${right_now}.sql.gz"

mysqldump -u"$mysql_user" -p"$mysql_pass" --all-databases > "${bk_fname}"
gzip -c "${bk_fname}" > "${bk_gzname}"
rm -f "${bk_fname}"
find "${bk_path}" -type f -mtime +7 | xargs rm -f

2. Ftp Backup Script
If script makes tar.gz archives for the specified files/folders, opens a remote ftp connection and send archives, removes archives from the last week and also sends backup logs to a specified email address.
I recommend to run this once a week with crontab
01 03 * * 1 php “/home/backups/ftp.php”

/*
 * FTP Backup tool
 * Makes local backups and send them through ftp on other server
 */

set_time_limit(0);
error_reporting(0);

// files/folders to backup
$backupThese  = array('uploads'=>'/home/public_html/uploads', 'database'=>'/home/backups/dumps');
$localFolder  = '/home/backups/archives/';
$remoteFolder = '/home/backups/';

// remote server
$ftpHost = 'ftp.remoteserver.net';
$ftpUser = '';
$ftpPass = '';
$ftpPort = 21;

// email errors
$email   = true;
$emailTo = 'youremail@domain.com';
$emailSj = 'Website Backup Log';
$emailHs = 'From: backupScript@domain.com' . "\r\n" .
    'Reply-To: noreply@domain.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

$emailMsg = '';
function LogThis($msg){

    global $log;
    global $emailMsg;

    $emailMsg .= $msg."\n\r";
    fwrite($log ,date('d.m.Y H:i:s', time()).": ".$msg."\n\r");
}

$log = fopen('/home/backups/backups.log', 'a+');
LogThis("START");

// create archives
foreach ($backupThese as $fileName => $filePath){

    // check if already archive
    if (array_pop(explode('.', $filePath))=='gz') continue;

    if (system('tar -zcvf '.$localFolder.date("mdY").$fileName.'.tar.gz '.$filePath)) {
        // archive created
        LogThis("Archive ".$fileName." created.");
    }
    else {
        // log archive error
        LogThis("Archive ".$fileName." error.");
    }
}

// transfers
if ($conn_id = ftp_connect($ftpHost, $ftpPort, 60)){
    if (ftp_login ($conn_id, $ftpUser, $ftpPass)){

        //ftp_pasv ($conn_id, true);

        foreach ($backupThese as $fileName => $filePath){

            // check if already archive
            if (array_pop(explode('.', $filePath))=='gz'){
                $localFile = $filePath;
            }
            else{
                $localFile = $localFolder.date("mdY").$fileName.'.tar.gz';
            }

            if (file_exists($localFile)){

                if (ftp_put ($conn_id, $remoteFolder.date("mdY").$fileName.'.tar.gz', $localFile, FTP_BINARY)){

                    LogThis("Archive ".$fileName." transfer OK.");
                    // delete last week backup on remote server
                    if (!ftp_delete($conn_id, $remoteFolder.date("mdY", time()-7*24*3600).$fileName.'.tar.gz')){
                        LogThis("Cannot delete last week ".$fileName." archive.");
                    }
                    if (!@unlink($localFolder.date("mdY").$fileName.'.tar.gz')){
                        LogThis("Cannot delete local ".$fileName." archive.");
                    }
                }
                else{
                    LogThis("Archive ".$fileName." transfer failed.");
                }
            }
            else{
                LogThis("Archive ".$filePath." doesn't exist.");
            }
        }

        ftp_close($conn_id);
    }
    else{
        LogThis("Ftp login failed.");
    }
}
else {
    LogThis("Ftp connection failed.");
}

fclose($log);

if ($email)
    @mail($emailTo, $emailSj, $emailMsg, $emailHs);

If you like this, please consider buying me a beer.

One Response to “Automatic Backups for Database and Files”

  1. admin Says:

    For RedHat 3.4.6-11:

    # backup.sh
    BKPATH=”/path/to/mysql/dumps”
    NOW=$(date +”%m-%d-%Y”)
    BKFNAME=”$BKPATH/backup.sql”
    BKGZNAME=”$BKPATH/dump.$NOW.sql.gz”

    mysqldump -u”user” -p”password” towns_common_III > “$BKFNAME”
    gzip -c “$BKFNAME” > “$BKGZNAME”
    rm -f “$BKFNAME”
    find “$BKPATH” -type f -mtime +10 | xargs rm -f