PHP 备份脚本
2010-06-22 19:28 by hackerzhou先感谢国家,后感谢某位我至今未曾谋面的同学。
昨天半改半写了php打包备份文件&备份数据库的小东东,代码不多,高手看了估计会笑话,用了一个开源的Zip类库pclzip,感觉挺方便的,不过压缩zip容易脚本超时,解决的方法就是把备份任务拆分,用header函数转向到子任务,像一个单向链表一样就可以了。
Mysql打包压缩代码(备份出来的文件可以用phpMyAdmin/mysqldump/MySQLAdministrator导入):
<?php $host="##mysql服务器地址##"; $user="##登录帐号##"; $password="##登录密码##"; $dbname="##数据库名##"; $filename="##备份文件路径##"; mysql_connect($host,$user,$password); mysql_select_db($dbname); $mysql.="CREATE DATABASE IF NOT EXISTS `".$dbname."`;\r\n"; $mysql.="USE `".$dbname."`;\r\n\r\n"; $q0=mysql_query("set names utf8"); $q1=mysql_query("show tables"); while($t=mysql_fetch_array($q1)){ $table=$t[0]; $mysql.="DROP TABLE IF EXISTS `".$table."`;\r\n"; $q2=mysql_query("show create table `$table`"); $sql=mysql_fetch_array($q2); $mysql.=$sql['Create Table'].";\r\n\r\n"; $q3=mysql_query("select * from `$table`"); while($data=mysql_fetch_assoc($q3)){ $keys=array_keys($data); $keys=array_map('addslashes',$keys); $keys=join('`,`',$keys); $keys="`".$keys."`"; $vals=array_values($data); $vals=array_map('addslashes',$vals); $vals=join("','",$vals); $vals="'".$vals."'"; $mysql.="insert into `$table`($keys) values($vals);\r\n"; } $mysql.="\r\n"; } $fp = fopen($filename,'wb'); fputs($fp,$mysql); fclose($fp); include_once('lib/pclzip.lib.php'); $archive = new PclZip($filename.'.zip'); $v_list = $archive->create($filename); if ($v_list == 0) { die("Error : ".$archive->errorInfo(true)); } if(file_exists($filename)){ unlink($filename); } echo "Mysql's backup successfully to ".$filename.".zip"; ?>
Zip打包备份代码,几乎就是全抄demo,太方便了:
<?PHP include_once('lib/pclzip.lib.php'); $src="##源路径##"; $dest="##目标zip路径##"; $archive = new PclZip($dest); $v_list = $archive->create($src); if ($v_list == 0) { die("Error : ".$archive->errorInfo(true)); }else{ print("Success"); } ?>
源代码已经Upload到Google Code http://hackerzhou.googlecode.com/files/PHPBackupScript.rar