php数据库备份类程序代码

今天没事收集了两款php数据库备份程序,这里可以完成功能有:1.备份指定数据表、2.打包成zip文件、3.发送到指定邮箱地址,基本功能就这些了.

下面看下使用方法,代码如下:

  1. <?php
  2. error_reporting(0);//消灭万恶的php报警提示
  3. //设定邮箱
  4. $options = array('email' => array('email1', 'email2'),
  5. 'folder' => './backup/',
  6. 'mysql' => array('localhost', 'user', 'password', 'db'));
  7. $b = new Backup($options);
  8. // 提交备份命令
  9. if(isset($_POST['backup']))
  10. {
  11. // 开始备份
  12. $b->backupDB();
  13. }
  14. // 显示备份表
  15. $b->outputForm();
  16. ?>

具体类实现,代码如下:

  1. <?php
  2. class Backup
  3. {
  4. /**
  5. * @var 用于保存配置参数
  6. */
  7. var $config;
  8. /**
  9. * @var 用于保存mysql dump的数据
  10. */
  11. var $dump;
  12. /**
  13. * @var 用于数据库结果数据以及insert指令
  14. */
  15. var $struktur = array();
  16. /**
  17. * @var 压缩文件名zip
  18. */
  19. var $datei;
  20. /**
  21. * 结构函数
  22. * 连接数据库
  23. * @return
  24. */
  25. public function Backup($options)
  26. {
  27. // 从形参中读取配置
  28. foreach($options AS $name => $value)
  29. {
  30. $this->config[$name] = $value;
  31. }
  32. // 连接数据库
  33. mysql_connect($this->config['mysql'][0], $this->config['mysql'][1],
  34. $this->config['mysql'][2]) or die(mysql_error());
  35. mysql_select_db($this->config['mysql'][3]) or die(mysql_error());
  36. }
  37. /**
  38. * 执行备份数据库流程的函数
  39. * @return
  40. */
  41. public function backupDB()
  42. {
  43. // 开始备份的命令
  44. if(isset($_POST['backup']))
  45. {
  46. // 检测是否选择了数据表
  47. if(emptyempty($_POST['table']))
  48. {
  49. die("请选择一个数据表。");
  50. }
  51. /** 开始备份 **/
  52. $tables = array();
  53. $insert = array();
  54. $sql_statement = '';
  55. // 锁定需要备份的数据库,防止读脏数据
  56. foreach($_POST['table'] AS $table)
  57. {
  58. mysql_query("LOCK TABLE $table WRITE");
  59. // 获取数据库结构
  60. $res = mysql_query('SHOW CREATE TABLE '.$table.'');
  61. $createtable = mysql_result($res, 0, 1);
  62. $str = "nn".$createtable."nn";
  63. array_push($tables, $str);
  64. // 查询数据表中的所有数据行
  65. $sql = 'SELECT * FROM '.$table;
  66. $query = mysql_query($sql) or die(mysql_error());
  67. $feld_anzahl = mysql_num_fields($query);
  68. $sql_statement = '--
  69. -- Data Table `$table`
  70. --
  71. ';
  72. // 开始读数据,并将其转换为insert命令
  73. while($ds = mysql_fetch_object($query)){
  74. $sql_statement .= 'INSERT INTO `'.$table.'` (';
  75. for ($i = 0;$i <$feld_anzahl;$i++){
  76. if ($i ==$feld_anzahl-1){
  77. $sql_statement .= mysql_field_name($query,$i);
  78. } else {
  79. $sql_statement .= mysql_field_name($query,$i).', ';
  80. }
  81. }
  82. $sql_statement .= ') VALUES (';
  83. for ($i = 0;$i <$feld_anzahl;$i++){
  84. $name = mysql_field_name($query,$i);
  85. if (emptyempty($ds->$name)){
  86. $ds->$name = 'NULL';
  87. }
  88. if ($i ==$feld_anzahl-1){
  89. $sql_statement .= '"'.$ds->$name.'"';
  90. } else {
  91. $sql_statement .= '"'.$ds->$name.'", ';
  92. }
  93. }
  94. $sql_statement .= ");n";
  95. }
  96. // 将insert数据放在数组中,去重
  97. if(!in_array($sql_statement, $insert))
  98. {
  99. array_push($insert, $sql_statement);
  100. unset($sql_statement);
  101. }
  102. unset($sql_statement);
  103. }
  104. // 将数据库结构与insert命令放在一起啦
  105. $this->struktur = array_combine($tables, $insert);
  106. // 执行dump函数
  107. $this->createDUMP($this->struktur);
  108. // 生成zip压缩包
  109. $this->createZIP();
  110. /** 备份结束 **/
  111. // 发一封邮件到指定邮箱,附件包含sql备份,如果你设置了的话^_^
  112. if(isset($this->config['email']) && !emptyempty($this->config['email']))
  113. {
  114. $this->sendEmail();
  115. }
  116. // output
  117. echo '<h3 >备份完成啦</h3><a href="'.
  118. $this->datei.'">下载备份</a>
  119. <br />
  120. <br />';
  121. }
  122. }
  123. /**
  124. * 发送邮件函数
  125. * @return
  126. */
  127. protected function sendEmail()
  128. {
  129. // 读取邮箱地址
  130. foreach($this->config['email'] AS $email)
  131. {
  132. $to = $email;
  133. $from = $this->config['email'][0];
  134. $message_body = "本邮件中包含的zip压缩包为数据库备份";
  135. $msep = strtoupper (md5 (uniqid (time ())));
  136. // 设置email头
  137. $header =
  138. "From: $fromrn" .
  139. "MIME-Version: 1.0rn" .
  140. "Content-Type: multipart/mixed; boundary=".$msep."rnrn" .
  141. "--$mseprn" .
  142. "Content-Type: text/plainrn" .
  143. "Content-Transfer-Encoding: 8bitrnrn" .
  144. $message_body . "rn";
  145. // 文件名
  146. $dateiname = $this->datei;
  147. // 压缩包大小
  148. $dateigroesse = filesize ($dateiname);
  149. // 读取压缩包
  150. $f = fopen ($dateiname, "r");
  151. // 保存到附件
  152. $attached_file = fread ($f, $dateigroesse);
  153. // 关闭压缩包
  154. fclose ($f);
  155. // 建立一个附件
  156. $attachment = chunk_split (base64_encode ($attached_file));
  157. // 设置附件头
  158. $header .=
  159. "--" . $msep . "rn" .
  160. "Content-Type: application/zip; name='Backup'rn" .
  161. "Content-Transfer-Encoding: base64rn" .
  162. "Content-Disposition: attachment; filename='Backup.zip'rn" .
  163. "Content-Description: Mysql Datenbank Backup im Anhangrnrn" .
  164. $attachment . "rn";
  165. // 标记附件结束未知
  166. $header .= "--$msep--";
  167. // 邮件标题
  168. $subject = "数据库备份";
  169. // 发送邮件需要开启php相应支持哦^^
  170. if(mail($to, $subject, '', $header) == FALSE)
  171. {
  172. die("无法发送邮件,请检查邮箱地址");
  173. }
  174. echo "<p><small>邮件发送成功</small></p>";
  175. }
  176. }
  177. /**
  178. * 建立数据库备份的压缩包并保存到服务器指定目录中
  179. * @return
  180. */
  181. protected function createZIP()
  182. {
  183. // 文件夹权限要够
  184. chmod($this->config['folder'], 0777);
  185. // 建立压缩包
  186. $zip = new ZipArchive();
  187. // 设置压缩包文件名
  188. $this->datei = $this->config['folder'].$this->config['mysql'][3]."_"
  189. .date("j_F_Y_g_i_a").".zip";
  190. // 看看压缩包能不能打开
  191. if ($zip->open($this->datei, ZIPARCHIVE::CREATE)!==TRUE) {
  192. exit("无法打开 <".$this->datei.">n");
  193. }
  194. // 把dump出来的数据放到压缩包里
  195. $zip->addFromString("dump.sql", $this->dump);
  196. // 关闭压缩包
  197. $zip->close();
  198. // 看看压缩包有没有生成
  199. if(!file_exists($this->datei))
  200. {
  201. die("无法生成压缩包");
  202. }
  203. echo "<p><small>数据库备份压缩包成功生成</small></p>";
  204. }
  205. /**
  206. * mysql dump函数
  207. * @param object $dump
  208. * @return
  209. */
  210. protected function createDUMP($dump)
  211. {
  212. $date = date("F j, Y, g:i a");
  213. $header = <<<HEADER
  214. -- SQL Dump
  215. --
  216. -- Host: {$_SERVER['HTTP_HOST']}
  217. -- Erstellungszeit: {$date}
  218. --
  219. -- Datenbank: `{$this->config['mysql'][3]}`
  220. --
  221. -- --------------------------------------------------------
  222. HEADER;
  223. foreach($dump AS $name => $value)
  224. {
  225. $sql .= $name.$value;
  226. }
  227. $this->dump = $header.$sql;
  228. }
  229. /**
  230. * 生成选择数据表的界面函数
  231. * @return
  232. */
  233. public function outputForm()
  234. {
  235. // 选择全部
  236. $result = mysql_list_tables($this->config['mysql'][3]);
  237. $buffer = '
  238. <fieldset>
  239. <legend>选择需要备份的数据表</legend>
  240. <form method="post" action="">
  241. <select name="table[]" multiple="multiple" size="30">';
  242. while($row = mysql_fetch_row($result))
  243. {
  244. $buffer .= '<option value="'.$row[0].'">'.$row[0].'</option>';
  245. }
  246. $buffer .= '</select>
  247. <br /><br />
  248. <input type="submit" name="backup" value="备份选定数据表" />
  249. </form>
  250. </fieldset>';
  251. echo $buffer;
  252. }
  253. }
  254. ?>

通用数据库备份类,代码如下:

  1. <?php
  2. /*数据库备份:NOTICE:此类要添加数据库连接才能正常工作*/
  3. Class Back_up_databaseextendsdbstuff{
  4. //类开始
  5. var $HOST;
  6. var $USERNAME;
  7. var $PASSWORD;
  8. var $DATABASE;
  9. function Back_up_database($host,$username,$password,$database){
  10. //初始化数据库连接
  11. $this->HOST=$host;
  12. $this->USERNAME=$username;
  13. $this->ASSWORD=$password;
  14. $this->DATABASE=$database;
  15. $Connection=$this->connect($this->HOST,$this->USERNAME,$this->ASSWORD,$this->DATABASE,$pconnect);
  16. $this->Connection=$Connection;
  17. }
  18. //取得数据库中的表
  19. function get_table_name($database){
  20. $this->Connection;
  21. $result=mysql_list_tables($database);
  22. $i=0;
  23. while($i<mysql_num_rows($result)){
  24. $tb_name[$i]=mysql_tablename($result,$i);
  25. $table_name.=$tb_name[$i].",";
  26. $i++;
  27. }
  28. $this->table_name=substr($table_name,0,-1);
  29. return$this->table_name;
  30. }
  31. //取得每个表中的FIELDS和属性并生成CREATETABLE语句
  32. function get_table_fields($table_name){
  33. $this->Connection;
  34. $createtable=dbstuff::query("SHOWCREATETABLE$table_name");
  35. $create=dbstuff::fetch_row($createtable);
  36. $tabledump.="DROPTABLEIFEXISTS$table_name;\n";
  37. $tabledump.=$create[1].";\n\n";
  38. $this->$table_name=$tabledump;
  39. return$this->$table_name;
  40. }
  41. //取得表中的数据并生成ISERTINTO语句
  42. function get_insert($table_insert_name){
  43. $this->Connection;
  44. $rows=dbstuff::query("SELECT*FROM$table_insert_name");
  45. $numfields=dbstuff::num_fields($rows);
  46. $numrows=dbstuff::num_rows($rows);
  47. while($row=dbstuff::fetch_row($rows)){
  48. $comma="";
  49. $tabledump.="INSERTINTO$table_insert_nameVALUES(";
  50. for($i=0;$i<$numfields;$i++){
  51. $tabledump.=$comma."'".mysql_escape_string($row[$i])."'";
  52. $comma=",";
  53. }
  54. $tabledump.=");\n";
  55. }
  56. $this->tabledump=$tabledump;
  57. return$this->tabledump;
  58. }
  59. //获取所有数据并连接成新的字符串并将它写入文件中.sql
  60. function get_string($database_name,$file_path_name){
  61. $time=date("Y-m-dH:j");
  62. $date_time=date("YmdHis");
  63. $file_path_name=$file_path_name.$date_time.".sql";
  64. $version="Antsent_Web_StudioDatabaseBackUpV1.01";
  65. $idstring='#Identify:'.base64_encode("$time,$version")."\n";
  66. $head_info="$idstring".
  67. "#\n".
  68. "#Antsnet_Web!TheBasicClassOfBackUpDataBase\n".
  69. "#Version:AntsnetWeb!$version\n".
  70. "#Timetime\n".
  71. "#Type:ClassOfBackUpDataBase\n".
  72. "#Antsnet_Web_Studio!Home:http://www.111cn.net \n".
  73. "#PleasevisitourwebsitefornewestinfomationaboutAntsnet_Web_Studio!\n".
  74. "#--------------------------------------------------------\n\n\n";
  75. $table_name=$this->get_table_name($database_name);
  76. $array_table=explode(",",$table_name);
  77. for($i=0;$i<count($array_table);$i++){
  78. $table_string.=$this->get_table_fields($array_table[$i]);
  79. $table_insert.=$this->get_insert($array_table[$i]);
  80. }
  81. $count_string=$head_info.$table_string.$table_insert;
  82. //return$count_string;
  83. $write_status=$this->write_file($file_path_name,$count_string);
  84. return$write_status;//开源代码phpfensi.com
  85. }
  86. //写入一个文件
  87. function write_file($file_path,$file_contents){
  88. if(@!$fp=fopen($file_path,'w')){
  89. $status="<fontcolor=\"red\">ThisFileCouldNotOpenOrRead.</font>";
  90. }else{
  91. flock($fp,3);
  92. fwrite($fp,$file_contents);
  93. fclose($fp);
  94. window.google_render_ad();
  95. ?>