Monday 19 November 2012

How to Schedule Database Backup Using Cron Job


Many Web Applications are changing daily. In case your site is hacked or its data becomes corrupted, it is beneficial to have regularly stored backups of your databases so you can restore your account quickly. Luckily, there is a quick and reliable way to do this through the use of Cron Jobs. Below is a step by step process on how to set up Cron Jobs to take backups of your Databases.

Change the following details to your database information and email information:
$dbhost = “localhost“; // leave this as localhost for most sites
$dbuser = “dbuser“; // enter your database username here
$dbpass = “dbpass“; // enter your database password here
$dbname = “dbname“; // enter the name of your database here
$sendto = “Send To <sendto @email.com>“; // the email address you are sending to
$sendfrom = “Send From <sendfrom @email.com>“; // This will be the reply to email address
$sendsubject = “Daily Database Backup“; // the subject of the email
$bodyofemail = “Here is the daily backup of my database.“; // The message included within the email

$backupfile = $dbname . date("Y-m-d") . '.sql.gz';
system("mysqldump -h $dbhost -u $dbuser --password=$dbpass $dbname | gzip > $backupfile");


Save the file and upload to “www” directory to your cPanel account.

Log into your cPanel. Locate and click on “Cron Jobs”



Set the Cron Job to run at the desired time, (it is usually best to run this through the middle of the night,) then put the following command in the “Command:” box with your username in place of “cPanelusername”

php -q ~/cPanelusername/public_html/mtebackup/backup.php




Your backup Cron Job will now be listed in the “Current Cron Jobs” section.

Enjoy receiving daily backups of your database.