MYSQL Database Backup using php

MYSQL Database Backup using php

Mysql database backup is one of the important task for web developer. Regular database backup prevent the data lose and
restore the data if any database issue occured. the database backup is good idea for backup the data.

The below code is very useful to backup the databse and mail to your personal mail. you can runt this file via cron jobs or any event click

just follow the below steps.

Step 1 : Create the file backup.php then store paste the below code. 

Step 2. Add $dbuser , $dbpwd , $dbname ,$to, $from details

Step 3. Then add the backup.php file in your server

Step 4. Run the backup.php file Database Backup file send to your personal mail.



$datestamp = date("Y-m-d");      // Current date to append to filename of backup file in format of YYYY-MM-DD

$dbuser = "";            // Database username
$dbpwd = "";            // Database password
$dbname = "";            // Database name. Use --all-databases if you have more than one
$filename= "backup-$datestamp.sql.gz";   // The name (and optionally path) of the dump file
$to = "";      // Email address to send dump file to
$from = "";      // Email address message will show as coming from.
$subject = "MySQL backup file";      // Subject of email

$command = "mysqldump -u $dbuser --password=$dbpwd $dbname | gzip > $filename";
$result = passthru($command);

$attachmentname = array_pop(explode("/", $filename));   // If a path was included, strip it out for the attachment name

$message = "Compressed database backup file $attachmentname attached.";
$mime_boundary = "< <<:" . md5(time());
$data = chunk_split(base64_encode(implode("", file($filename))));

$headers = "From: $from ";
$headers .= "MIME-Version: 1.0 ";
$headers .= "Content-type: multipart/mixed; ";
$headers .= " boundary="".$mime_boundary."" ";

$content = "This is a multi-part message in MIME format. ";
$content.= "--".$mime_boundary." ";
$content.= "Content-Type: text/plain; charset="iso-8859-1" ";
$content.= "Content-Transfer-Encoding: 7bit ";
$content.= $message." ";
$content.= "--".$mime_boundary." ";
$content.= "Content-Disposition: attachment; ";
$content.= "Content-Type: Application/Octet-Stream; name="$attachmentname" ";
$content.= "Content-Transfer-Encoding: base64 ";
$content.= $data." ";
$content.= "--" . $mime_boundary . " ";

mail($to, $subject, $content, $headers);

unlink($filename);   //delete the backup file from the server



Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed