本方法只适用数据量较少的网站,数据量大的网站请考虑其他可行方案!
此脚本将向您发送一封电子邮件,附带一个 .sql 文件,从而使您能够轻松地备份特定的表。如果你有一个数据库驱动的网站,你的 MySQL 信息是最有价值的,您甚至可以设置一个电子邮件帐户来接收这些备份。
首先,如果您将脚本放置在一个非 Web 访问的文件夹中,并在其上运行每日 cron 自动定时作业,此脚本的工作效果最好。Cron 是一个服务器工具,可以定期或在指定的时间运行脚本,因此您不需要在浏览器中调用它们。
这个脚本的已知限制:如果您有一个超过2mb的大型数据库表,您可能会遇到php超时和php邮件附件限制。
- // 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 = "Daily Mysql Backup";
- $bodyofemail = "Here is the daily backup.";
- // don't need to edit below this section
-
- $backupfile = $dbname . date("Y-m-d") . '.sql';
- system("mysqldump -h $dbhost -u $dbuser -p$dbpass $dbname > $backupfile");
-
- // Mail the file
-
- include( 'Mail.php' );
- include( 'Mail/mime.php' );
-
- $message = new Mail_mime();
- $text = "$bodyofemail";
- $message->setTXTBody( $text );
- $message->AddAttachment( $backupfile );
- $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);