How to e-mail yourself an automatic backup of your MySQL database table with PHP 

This script will send an e-mail to you with an gzipped .sql file attached, thus enabling you to back up specific tables easily. You could even set up an e-mail account just to receive these backups…

This script works best if you place it in a non-web accessible folder and run a daily cron job on it. Cron is a server “tool” that can run scripts regularly or at specified times (thus you don’t need to call them in your browser).

The code is below, and requires the Pear Mime and Pear Mail packages.
Known limitations of this script: if you have a big database table over 2mb, you will probably run into php timeouts and php mail attachment limits.

<code>
<?php
// Inspired by tutorials: http://www.phpfreaks.com/tutorials/130/6.php
// http://www.vbulletin.com/forum/archive/index.php/t-113143.html
// http://hudzilla.org
// temporary show errors
error_reporting(E_ALL);
ini_set("display_errors", 1);

// Create the mysql backup file
// edit this section
$dbhost = "yourhost"; // usually localhost
$dbuser = "yourusername";
$dbpass = "yourpassword";
$dbname = "yourdb";
$sendto = "Webmaster <webmaster@yourdomain.com>";
$sendfrom = "Automated Backup <backup@yourdomain.com>";
$sendsubject = "Mysql Backup";
$bodyofemail = "Here is the backup.";
// don't need to edit below this section

$backupfile = $dbname.date("Y-m-d").'.sql';
$backupzip = $backupfile.'.tar.gz';
system("mysqldump -h $dbhost -u $dbuser -p$dbpass $dbname > $backupfile");
echo 'Created '.$backupfile.' of size '.filesize($backupfile)." bytes<br />\n";
system("tar -czf $backupzip $backupfile");
echo 'Created '.$backupzip.' of size '.filesize($backupzip)." bytes<br />\n";

// Mail the file

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

$message = new Mail_mime();
$text = "$bodyofemail";
$message->setTXTBody($text);
$message->AddAttachment($backupzip);
$body = $message->get();
$extraheaders = array("From"=>"$sendfrom", "Subject"=>"$sendsubject");
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send("$sendto", $headers, $body);


// Delete the file from your server
unlink($backupfile);
echo 'Deleted file '.$backupfile."<br />\n";
unlink($backupzip);
echo 'Deleted file '.$backupzip."<br />\n";
?>

</code>