Backup MySQL database & email results using 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');

	// location of your temp directory
	$tmpDir = "/tmp/";
	// username for MySQL
	$user = "root";
	// password for MySQl
	$password = "pass";
	// database name to backup
	$dbName = "db";
	// the zip file emailed to you will have this prefixed
	$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);

?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s