PHP database backup class share a good PHP database backup class

Source: Internet
Author: User
Tags php database ziparchive
    1. error_reporting (0);//Eliminate all the evils of PHP alarm tips
    2. Set mailbox
    3. $options = Array (' email ' = = Array (' Email1 ', ' email2 '),
    4. ' Folder ' = './backup/',
    5. ' MySQL ' = array (' localhost ', ' user ', ' password ', ' db ');
    6. $b = new Backup ($options);
    7. Submit Backup Command
    8. if (isset ($_post[' backup '))
    9. {
    10. Start Backup
    11. $b->backupdb ();
    12. }
    13. Show Backup Table
    14. $b->outputform ();
    15. ?>
Copy Code

Implementation code for the PHP database backup class:

  1. /**
  2. * Backup MySQL Database
  3. * edit:bbs.it-home.org
  4. */
  5. Class Backup
  6. {
  7. /**
  8. * @var to save configuration parameters
  9. */
  10. var $config;
  11. /**
  12. * @var to save MySQL dump data
  13. */
  14. var $dump;
  15. /**
  16. * @var for database result data and insert Directives
  17. */
  18. var $struktur = array ();
  19. /**
  20. * @var Compressed file name zip
  21. */
  22. var $datei;
  23. /**
  24. * Structure function
  25. * Connect to Database
  26. * @return
  27. */
  28. Public Function Backup ($options)
  29. {
  30. Reading the configuration from the formal parameter
  31. foreach ($options as $name = $value)
  32. {
  33. $this->config[$name] = $value;
  34. }
  35. Connecting to a database
  36. mysql_connect ($this->config[' MySQL '][0], $this->config[' MySQL '][1],
  37. $this->config[' MySQL '][2]) or Die (Mysql_error ());
  38. mysql_select_db ($this->config[' MySQL '][3]) or Die (Mysql_error ());
  39. }
  40. /**
  41. * Functions to perform backup database processes
  42. * @return
  43. */
  44. Public Function backupdb ()
  45. {
  46. command to start Backup
  47. if (isset ($_post[' backup '))
  48. {
  49. Detects if a data table is selected
  50. if (Empty ($_post[' table ']))
  51. {
  52. Die ("Please select a data table.) ");
  53. }
  54. /** Start Backup **/
  55. $tables = Array ();
  56. $insert = Array ();
  57. $sql _statement = ";
  58. Lock the database that needs to be backed up to prevent read dirty data
  59. foreach ($_post[' table '] as $table)
  60. {
  61. mysql_query ("LOCK TABLE $table WRITE");
  62. Get the database structure
  63. $res = mysql_query (' SHOW CREATE TABLE '. $table. ');
  64. $createtable = mysql_result ($res, 0, 1);
  65. $str = "\ n". $createtable. " \ n ";
  66. Array_push ($tables, $STR);
  67. Querying all data rows in a data table
  68. $sql = ' SELECT * from '. $table;
  69. $query = mysql_query ($sql) or Die (Mysql_error ());
  70. $feld _anzahl = Mysql_num_fields ($query);
  71. $sql _statement = '--
  72. --Data Table ' $table '
  73. --
  74. ';
  75. Start reading the data and convert it to the Insert command
  76. while ($ds = Mysql_fetch_object ($query)) {
  77. $sql _statement. = ' INSERT into '. $table. ' ` (';
  78. for ($i = 0; $i < $feld _anzahl; $i + +) {
  79. if ($i = = $feld _anzahl-1) {
  80. $sql _statement. = Mysql_field_name ($query, $i);
  81. } else {
  82. $sql _statement. = Mysql_field_name ($query, $i). ', ';
  83. }
  84. }
  85. $sql _statement. = ') VALUES (';
  86. for ($i = 0; $i < $feld _anzahl; $i + +) {
  87. $name = Mysql_field_name ($query, $i);
  88. if (Empty ($ds-$name)) {
  89. $ds $name = ' NULL ';
  90. }
  91. if ($i = = $feld _anzahl-1) {
  92. $sql _statement. = ' "'. $ds, $name. '";
  93. } else {
  94. $sql _statement. = "'. $ds, $name. ', ';
  95. }
  96. }
  97. $sql _statement. = "); \ n";
  98. }
  99. Put the insert data in the array and go back to the
  100. if (!in_array ($sql _statement, $insert))
  101. {
  102. Array_push ($insert, $sql _statement);
  103. unset ($sql _statement);
  104. }
  105. unset ($sql _statement);
  106. }
  107. Put the database structure together with the Insert command
  108. $this->struktur = Array_combine ($tables, $insert);
  109. Execute Dump function
  110. $this->createdump ($this->struktur);
  111. Generate a ZIP archive package
  112. $this->createzip ();
  113. /** Backup End **/
  114. Send an email to the specified mailbox, the attachment contains the SQL backup, if you set the word ^_^
  115. if (isset ($this->config[' email ') &&!empty ($this->config[' email '))
  116. {
  117. $this->sendemail ();
  118. }
  119. Output
  120. Echo '

    Backup done.

    $this->datei. ' " > Download Backup


  121. ';
  122. }
  123. }
  124. /**
  125. * Send mail function
  126. * @return
  127. */
  128. protected function SendEmail ()
  129. {
  130. Read e-mail address
  131. foreach ($this->config[' email ') as $email)
  132. {
  133. $to = $email;
  134. $from = $this->config[' email '][0];
  135. $message _body = "The zip archive contained in this message is a database backup";
  136. $MSEP = Strtoupper (MD5 (Uniqid (Time ()));
  137. Set up an email header
  138. $header =
  139. "From: $from \ r \ n".
  140. "Mime-version:1.0\r\n".
  141. "Content-type:multipart/mixed; Boundary= ". $msep." \r\n\r\n ".
  142. "--$msep \ r \ n".
  143. "Content-type:text/plain\r\n".
  144. "Content-transfer-encoding:8bit\r\n\r\n".
  145. $message _body. "\ r \ n";
  146. Filename
  147. $dateiname = $this->datei;
  148. Compress Package Size
  149. $dateigroesse = FileSize ($dateiname);
  150. Reading a compressed package
  151. $f = fopen ($dateiname, "R");
  152. Save to Attachment
  153. $attached _file = fread ($f, $dateigroesse);
  154. To close a compressed package
  155. Fclose ($f);
  156. Create an attachment
  157. $attachment = Chunk_split (Base64_encode ($attached _file));
  158. Set Attachment header
  159. $header. =
  160. "--" . $msep. "\ r \ n".
  161. "Content-type:application/zip; Name= ' Backup ' \ r \ n '.
  162. "Content-transfer-encoding:base64\r\n".
  163. "Content-disposition:attachment; Filename= ' backup.zip ' \ r \ n '.
  164. "Content-description:mysql Datenbank Backup im anhang\r\n\r\n".
  165. $attachment. "\ r \ n";
  166. Tag Attachment End Unknown
  167. $header. = "--$msep--";
  168. Message header
  169. $subject = "Database Backup";
  170. Send the message need to open PHP corresponding support Oh ^ ^
  171. if (Mail ($to, $subject, ', $header) = = FALSE)
  172. {
  173. Die ("Unable to send mail, please check email address");
  174. }
  175. echo "

    Message sent successfully

    ";
  176. }
  177. }
  178. /**
  179. * Set up the database backup package and save it to the server specified directory
  180. * @return
  181. */
  182. protected function Createzip ()
  183. {
  184. folder permissions are sufficient
  185. chmod ($this->config[' folder '], 0777);
  186. Creating a compressed Package
  187. $zip = new Ziparchive ();
  188. Set file name for compressed package
  189. $this->datei = $this->config[' folder ']. $this->config[' MySQL '][3]. " _"
  190. . Date ("J_f_y_g_i_a"). ". Zip ";
  191. Let's see if the compression pack opens.
  192. if ($zip->open ($this->datei, ziparchive::create)!==true) {
  193. Exit ("Cannot open <". $this->datei. " >\n ");
  194. }
  195. Put the dump data in the compression pack.
  196. $zip->addfromstring ("Dump.sql", $this->dump);
  197. To close a compressed package
  198. $zip->close ();
  199. See if the compression pack is generated
  200. if (!file_exists ($this->datei))
  201. {
  202. Die ("Unable to generate a compressed package");
  203. }
  204. echo "

    Database backup compression package successfully generated

    ";
  205. }
  206. /**
  207. * MySQL dump function
  208. * @param object $dump
  209. * @return
  210. */
  211. protected function Createdump ($dump)
  212. {
  213. $date = Date ("F J, Y, g:i a");
  214. $header = <<<>
  215. --SQL Dump
  216. --
  217. --Host: {$_server[' Http_host '}
  218. --Erstellungszeit: {$date}
  219. --
  220. --Datenbank: ' {$this->config[' mysql '][3]} '
  221. --
  222. -- --------------------------------------------------------
  223. HEADER;
  224. foreach ($dump as $name = $value)
  225. {
  226. $sql. = $name. $value;
  227. }
  228. $this->dump = $header. $sql;
  229. }
  230. /**
  231. * Interface function to generate the selection data table
  232. * @return
  233. */
  234. Public Function Outputform ()
  235. {
  236. Select All
  237. $result = mysql_list_tables ($this->config[' MySQL '][3]);
  238. $buffer = '
  239. Select the data table you want to back up
  240. ';
  241. Echo $buffer;
  242. }
  243. }
  244. ?>
Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.