Thursday, August 27, 2009

How to: Backup MySQL database & email results using PHP

SkyHi @ Thursday, August 27, 2009
There are a bunch of scripts on the Internet that overly complicate the issue of automatically backing up your database. Here is a PHP script I wrote to backup a mysql database and email the results. Just set a cron job (/etc/crontab) to run this script with the following command: php /…./dbBackUp.php


<?php

/*

Quickly and easily backup your MySQL database and have the tgz emailed to you. You need PEAR installed with the Mail and Mail_Mime packages installed. Read more about PEAR here: http://pear.php.net. This will work in any *nix enviornment. Make sure you have write access to your /tmp directory.

*/

require_once('Mail.php');
require_once('Mail/mime.php');

// mysql & minor details..
$tmpDir = "/tmp/";
$user = "root";
$password = "pass";
$dbName = "db";
$prefix = "db_";

// email settings...
$to = "someone@gmail.com";
$from = "another@gmail.com";
$subject = "db - backup";
$sqlFile = $tmpDir.$prefix.date('Y_m_d').".sql";
$attachment = $tmpDir.$prefix.date('Y_m_d').".tgz";

$creatBackup = "mysqldump -u ".$user." --password=".$password." ".$dbName." > ".$sqlFile;
$createZip = "tar cvzf $attachment $sqlFile";
exec($creatBackup);
exec($createZip);

$headers = array('From' => $from, 'Subject' => $subject);
$textMessage = $attachment;
$htmlMessage = "";

$mime = new Mail_Mime("\n");
$mime->setTxtBody($textMessage);
$mime->setHtmlBody($htmlMessage);
$mime->addAttachment($attachment, 'text/plain');
$body = $mime->get();
$hdrs = $mime->headers($headers);
$mail = &Mail::factory('mail');
$mail->send($to, $hdrs, $body);

unlink($sqlFile);
unlink($attachment);

?>



Reference: http://www.sematopia.com/?p=61