php数据库备份类程序代码
今天没事收集了两款php数据库备份程序,这里可以完成功能有:1.备份指定数据表、2.打包成zip文件、3.发送到指定邮箱地址,基本功能就这些了.
下面看下使用方法,代码如下:
- <?php
- error_reporting(0);//消灭万恶的php报警提示
- //设定邮箱
- $options = array('email' => array('email1', 'email2'),
- 'folder' => './backup/',
- 'mysql' => array('localhost', 'user', 'password', 'db'));
- $b = new Backup($options);
- // 提交备份命令
- if(isset($_POST['backup']))
- {
- // 开始备份
- $b->backupDB();
- }
- // 显示备份表
- $b->outputForm();
- ?>
具体类实现,代码如下:
- <?php
- class Backup
- {
- /**
- * @var 用于保存配置参数
- */
- var $config;
- /**
- * @var 用于保存mysql dump的数据
- */
- var $dump;
- /**
- * @var 用于数据库结果数据以及insert指令
- */
- var $struktur = array();
- /**
- * @var 压缩文件名zip
- */
- var $datei;
- /**
- * 结构函数
- * 连接数据库
- * @return
- */
- public function Backup($options)
- {
- // 从形参中读取配置
- foreach($options AS $name => $value)
- {
- $this->config[$name] = $value;
- }
- // 连接数据库
- mysql_connect($this->config['mysql'][0], $this->config['mysql'][1],
- $this->config['mysql'][2]) or die(mysql_error());
- mysql_select_db($this->config['mysql'][3]) or die(mysql_error());
- }
- /**
- * 执行备份数据库流程的函数
- * @return
- */
- public function backupDB()
- {
- // 开始备份的命令
- if(isset($_POST['backup']))
- {
- // 检测是否选择了数据表
- if(emptyempty($_POST['table']))
- {
- die("请选择一个数据表。");
- }
- /** 开始备份 **/
- $tables = array();
- $insert = array();
- $sql_statement = '';
- // 锁定需要备份的数据库,防止读脏数据
- foreach($_POST['table'] AS $table)
- {
- mysql_query("LOCK TABLE $table WRITE");
- // 获取数据库结构
- $res = mysql_query('SHOW CREATE TABLE '.$table.'');
- $createtable = mysql_result($res, 0, 1);
- $str = "nn".$createtable."nn";
- array_push($tables, $str);
- // 查询数据表中的所有数据行
- $sql = 'SELECT * FROM '.$table;
- $query = mysql_query($sql) or die(mysql_error());
- $feld_anzahl = mysql_num_fields($query);
- $sql_statement = '--
- -- Data Table `$table`
- --
- ';
- // 开始读数据,并将其转换为insert命令
- while($ds = mysql_fetch_object($query)){
- $sql_statement .= 'INSERT INTO `'.$table.'` (';
- for ($i = 0;$i <$feld_anzahl;$i++){
- if ($i ==$feld_anzahl-1){
- $sql_statement .= mysql_field_name($query,$i);
- } else {
- $sql_statement .= mysql_field_name($query,$i).', ';
- }
- }
- $sql_statement .= ') VALUES (';
- for ($i = 0;$i <$feld_anzahl;$i++){
- $name = mysql_field_name($query,$i);
- if (emptyempty($ds->$name)){
- $ds->$name = 'NULL';
- }
- if ($i ==$feld_anzahl-1){
- $sql_statement .= '"'.$ds->$name.'"';
- } else {
- $sql_statement .= '"'.$ds->$name.'", ';
- }
- }
- $sql_statement .= ");n";
- }
- // 将insert数据放在数组中,去重
- if(!in_array($sql_statement, $insert))
- {
- array_push($insert, $sql_statement);
- unset($sql_statement);
- }
- unset($sql_statement);
- }
- // 将数据库结构与insert命令放在一起啦
- $this->struktur = array_combine($tables, $insert);
- // 执行dump函数
- $this->createDUMP($this->struktur);
- // 生成zip压缩包
- $this->createZIP();
- /** 备份结束 **/
- // 发一封邮件到指定邮箱,附件包含sql备份,如果你设置了的话^_^
- if(isset($this->config['email']) && !emptyempty($this->config['email']))
- {
- $this->sendEmail();
- }
- // output
- echo '<h3 >备份完成啦</h3><a href="'.
- $this->datei.'">下载备份</a>
- <br />
- <br />';
- }
- }
- /**
- * 发送邮件函数
- * @return
- */
- protected function sendEmail()
- {
- // 读取邮箱地址
- foreach($this->config['email'] AS $email)
- {
- $to = $email;
- $from = $this->config['email'][0];
- $message_body = "本邮件中包含的zip压缩包为数据库备份";
- $msep = strtoupper (md5 (uniqid (time ())));
- // 设置email头
- $header =
- "From: $fromrn" .
- "MIME-Version: 1.0rn" .
- "Content-Type: multipart/mixed; boundary=".$msep."rnrn" .
- "--$mseprn" .
- "Content-Type: text/plainrn" .
- "Content-Transfer-Encoding: 8bitrnrn" .
- $message_body . "rn";
- // 文件名
- $dateiname = $this->datei;
- // 压缩包大小
- $dateigroesse = filesize ($dateiname);
- // 读取压缩包
- $f = fopen ($dateiname, "r");
- // 保存到附件
- $attached_file = fread ($f, $dateigroesse);
- // 关闭压缩包
- fclose ($f);
- // 建立一个附件
- $attachment = chunk_split (base64_encode ($attached_file));
- // 设置附件头
- $header .=
- "--" . $msep . "rn" .
- "Content-Type: application/zip; name='Backup'rn" .
- "Content-Transfer-Encoding: base64rn" .
- "Content-Disposition: attachment; filename='Backup.zip'rn" .
- "Content-Description: Mysql Datenbank Backup im Anhangrnrn" .
- $attachment . "rn";
- // 标记附件结束未知
- $header .= "--$msep--";
- // 邮件标题
- $subject = "数据库备份";
- // 发送邮件需要开启php相应支持哦^^
- if(mail($to, $subject, '', $header) == FALSE)
- {
- die("无法发送邮件,请检查邮箱地址");
- }
- echo "<p><small>邮件发送成功</small></p>";
- }
- }
- /**
- * 建立数据库备份的压缩包并保存到服务器指定目录中
- * @return
- */
- protected function createZIP()
- {
- // 文件夹权限要够
- chmod($this->config['folder'], 0777);
- // 建立压缩包
- $zip = new ZipArchive();
- // 设置压缩包文件名
- $this->datei = $this->config['folder'].$this->config['mysql'][3]."_"
- .date("j_F_Y_g_i_a").".zip";
- // 看看压缩包能不能打开
- if ($zip->open($this->datei, ZIPARCHIVE::CREATE)!==TRUE) {
- exit("无法打开 <".$this->datei.">n");
- }
- // 把dump出来的数据放到压缩包里
- $zip->addFromString("dump.sql", $this->dump);
- // 关闭压缩包
- $zip->close();
- // 看看压缩包有没有生成
- if(!file_exists($this->datei))
- {
- die("无法生成压缩包");
- }
- echo "<p><small>数据库备份压缩包成功生成</small></p>";
- }
- /**
- * mysql dump函数
- * @param object $dump
- * @return
- */
- protected function createDUMP($dump)
- {
- $date = date("F j, Y, g:i a");
- $header = <<<HEADER
- -- SQL Dump
- --
- -- Host: {$_SERVER['HTTP_HOST']}
- -- Erstellungszeit: {$date}
- --
- -- Datenbank: `{$this->config['mysql'][3]}`
- --
- -- --------------------------------------------------------
- HEADER;
- foreach($dump AS $name => $value)
- {
- $sql .= $name.$value;
- }
- $this->dump = $header.$sql;
- }
- /**
- * 生成选择数据表的界面函数
- * @return
- */
- public function outputForm()
- {
- // 选择全部
- $result = mysql_list_tables($this->config['mysql'][3]);
- $buffer = '
- <fieldset>
- <legend>选择需要备份的数据表</legend>
- <form method="post" action="">
- <select name="table[]" multiple="multiple" size="30">';
- while($row = mysql_fetch_row($result))
- {
- $buffer .= '<option value="'.$row[0].'">'.$row[0].'</option>';
- }
- $buffer .= '</select>
- <br /><br />
- <input type="submit" name="backup" value="备份选定数据表" />
- </form>
- </fieldset>';
- echo $buffer;
- }
- }
- ?>
通用数据库备份类,代码如下:
- <?php
- /*数据库备份:NOTICE:此类要添加数据库连接才能正常工作*/
- Class Back_up_databaseextendsdbstuff{
- //类开始
- var $HOST;
- var $USERNAME;
- var $PASSWORD;
- var $DATABASE;
- function Back_up_database($host,$username,$password,$database){
- //初始化数据库连接
- $this->HOST=$host;
- $this->USERNAME=$username;
- $this->ASSWORD=$password;
- $this->DATABASE=$database;
- $Connection=$this->connect($this->HOST,$this->USERNAME,$this->ASSWORD,$this->DATABASE,$pconnect);
- $this->Connection=$Connection;
- }
- //取得数据库中的表
- function get_table_name($database){
- $this->Connection;
- $result=mysql_list_tables($database);
- $i=0;
- while($i<mysql_num_rows($result)){
- $tb_name[$i]=mysql_tablename($result,$i);
- $table_name.=$tb_name[$i].",";
- $i++;
- }
- $this->table_name=substr($table_name,0,-1);
- return$this->table_name;
- }
- //取得每个表中的FIELDS和属性并生成CREATETABLE语句
- function get_table_fields($table_name){
- $this->Connection;
- $createtable=dbstuff::query("SHOWCREATETABLE$table_name");
- $create=dbstuff::fetch_row($createtable);
- $tabledump.="DROPTABLEIFEXISTS$table_name;\n";
- $tabledump.=$create[1].";\n\n";
- $this->$table_name=$tabledump;
- return$this->$table_name;
- }
- //取得表中的数据并生成ISERTINTO语句
- function get_insert($table_insert_name){
- $this->Connection;
- $rows=dbstuff::query("SELECT*FROM$table_insert_name");
- $numfields=dbstuff::num_fields($rows);
- $numrows=dbstuff::num_rows($rows);
- while($row=dbstuff::fetch_row($rows)){
- $comma="";
- $tabledump.="INSERTINTO$table_insert_nameVALUES(";
- for($i=0;$i<$numfields;$i++){
- $tabledump.=$comma."'".mysql_escape_string($row[$i])."'";
- $comma=",";
- }
- $tabledump.=");\n";
- }
- $this->tabledump=$tabledump;
- return$this->tabledump;
- }
- //获取所有数据并连接成新的字符串并将它写入文件中.sql
- function get_string($database_name,$file_path_name){
- $time=date("Y-m-dH:j");
- $date_time=date("YmdHis");
- $file_path_name=$file_path_name.$date_time.".sql";
- $version="Antsent_Web_StudioDatabaseBackUpV1.01";
- $idstring='#Identify:'.base64_encode("$time,$version")."\n";
- $head_info="$idstring".
- "#\n".
- "#Antsnet_Web!TheBasicClassOfBackUpDataBase\n".
- "#Version:AntsnetWeb!$version\n".
- "#Timetime\n".
- "#Type:ClassOfBackUpDataBase\n".
- "#Antsnet_Web_Studio!Home:http://www.111cn.net \n".
- "#PleasevisitourwebsitefornewestinfomationaboutAntsnet_Web_Studio!\n".
- "#--------------------------------------------------------\n\n\n";
- $table_name=$this->get_table_name($database_name);
- $array_table=explode(",",$table_name);
- for($i=0;$i<count($array_table);$i++){
- $table_string.=$this->get_table_fields($array_table[$i]);
- $table_insert.=$this->get_insert($array_table[$i]);
- }
- $count_string=$head_info.$table_string.$table_insert;
- //return$count_string;
- $write_status=$this->write_file($file_path_name,$count_string);
- return$write_status;//开源代码phpfensi.com
- }
- //写入一个文件
- function write_file($file_path,$file_contents){
- if(@!$fp=fopen($file_path,'w')){
- $status="<fontcolor=\"red\">ThisFileCouldNotOpenOrRead.</font>";
- }else{
- flock($fp,3);
- fwrite($fp,$file_contents);
- fclose($fp);
- window.google_render_ad();
- ?>