Home > Web Development > Automated MySQL backup in PHP

Automated MySQL backup in PHP

November 27th, 2009

Even though most shared web hosting providers offer free backup with basic packages we cannot fully rely on them as they schedule the backup only once in a week.

So a hard disk failure or malware attack may spoil your recent data.

If you have multiple hosting accounts then it is easy to setup a server to server automated backup system with this simple code.

<?php
$host = “localhost”;
$db=”server_db”;
$dbuser = “server_adm”;
$dbpswd = “password”;

$filename = $db .”.sql”;

if ( file_exists($filename) ) unlink($filename);  //delete the backup if exists

system(“mysqldump –user=$dbuser –password=$dbpswd –host=$host $mysqldb > $filename”,$result); //run backup

$conn_id = ftp_connect(“otherserver.com”); //connect to second sever

$login_result = ftp_login($conn_id, “backup@otherserver.com”, “password”);

ftp_put($conn_id, $filename, $filename, FTP_ASCII); //copy the backup to the second server

ftp_close($conn_id);
}
?>

This simple script creates a backup on the local server directory using mysqldump command, then connect to the second server using ftp and copies the file to the second server.

To automate this step you have to run this script using cron (refer control panel docs for adding a cron entry).

No related posts.

Web Development , , , ,

Comments are closed.