Backup MySQL database & email results using PHP

This specific post was one that I decided to do, only because I thought I would never use it. This specific tool worked out great and allows users to have there SQL databases emailed to them. Now you are wondering why would somebody use this. Well it’s simple. I needed this specific tool only to back up certain tables in my SQL database, so that the results could be used in a CSV format and then reloaded on a C++ platform. Without me having to do it manually ever time.

So in short the sql is emailed then piped to a written program allowing a up-to-date version of members from the live site. Sounds pretty neat….

( Please note I changed the code slightly to work for me, but posted the original version. )

Here’s the code:

 
< ?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);

?>

To download the script click here. (special thanks to sematopia.com )

admin No comments
Leave a comment

Tensor is a sleek template that can fit many different websites. It can have a…

Levante is a simple, clean, minimalist and modern template suitable for business and corporate sites….

3 Column layout Joomla 1.5 template. This Joomla template has lots of parameters. Easy to…

Scorpii is a modern and professional Joomla 1.5 template suitable for business and corporate sites….

Azimuth is a clean template best suited for business and corporate websites. It has subtle…