Home > Linux Howtos, Programming > How backup and email MySQL databases with Cron and PHP.

How backup and email MySQL databases with Cron and PHP.

June 14th, 2009 Jimmy

Here is a PHP script I wrote to backup my mySQL databases. Just use a cron job to run the PHP script when you want. The PHP MySQL database backup script will also email the database. With a Google Gmail account you get more than 7 gigs of storage so they are a good service for using for your backups.

<?php
error_reporting(0);

$dbuser=”root”;
$dbhost=”localhost”;
$dbname=”my_db”;
$dbpass=”";
$email_to = “someemail@gmail.com”; // Who the email is too
$bu_path = /path/to/backups;

//Lets set a date stamp to the MySQL database.
$backupFile = $dbname . date(“Y-m-d-H-i-s”) . ‘.sql’;

//Lets set a date stamp to the file name.
$zipFile = $dbname . date(“Y-m-d-H-i-s”) . ‘.zip’;

//BACKUP section
$command = “mysqldump –opt -h $dbhost -u $dbuser –password=$dbpass $dbname > $bu_path/$backupFile”;
system($command);

$zipcom = “zip -r -9 $bu_path/$zipFile $bu_path/$backupFile”;
system($zipcom);

$remcom = “rm $bu_path/$backupFile”;
system($remcom);

//EMAIL SECTION
$fileatt = “$bu_path/$zipFile”; // Path to the file
$fileatt_type = “application/x-zip-compressed”; // File Type
$fileatt_name = “$zipFile”; // Filename that will be used for the file as the attachment

$email_from = “noreply@prowhowto.net”; // Who the email is from
$email_subject = “DB Backup”; // The Subject of the email
$email_txt = “Attached should be the sql backup.”; // Message that the email has in it

$headers = “From: “.$email_from;

$file = fopen($fileatt,’rb’);
$data = fread($file,filesize($fileatt));
fclose($file);

$semi_rand = md5(time());
$mime_boundary = “==Multipart_Boundary_x{$semi_rand}x”;

$headers .= “\nMIME-Version: 1.0\n” .
“Content-Type: multipart/mixed;\n” .
” boundary=\”{$mime_boundary}\”";

$email_message .= “This is a multi-part message in MIME format.\n\n” .
“–{$mime_boundary}\n” .
“Content-Type:text/html; charset=\”iso-8859-1\”\n” .
“Content-Transfer-Encoding: 7bit\n\n” .
$email_message . “\n\n”;

$data = chunk_split(base64_encode($data));
$email_message .= “–{$mime_boundary}\n” .
“Content-Type: {$fileatt_type};\n” .
” name=\”{$fileatt_name}\”\n” .
“Content-Transfer-Encoding: base64\n\n” .
$data . “\n\n” .
“–{$mime_boundary}–\n”;

$ok = @mail($email_to, $email_subject, $email_message, $headers);

?>

Categories: Linux Howtos, Programming Tags: ,
Digg: DIGG ME
Comments are closed.