Home > Backend Development > PHP Tutorial > PHP database backup class Share a good PHP database backup class

PHP database backup class Share a good PHP database backup class

WBOY
Release: 2016-07-25 08:56:00
Original
1119 people have browsed it
  1. error_reporting(0);//Eliminate all evil php alarm prompts
  2. //Set email address
  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. // Display backup Table
  14. $b->outputForm();
  15. ?>
Copy code

PHP database backup class implementation code:

  1. /**
  2. * Back up mysql database
  3. * edit: bbs.it-home.org
  4. */
  5. class Backup
  6. {
  7. /**
  8. * @var is used to save configuration parameters
  9. */
  10. var $config;
  11. /**
  12. * @var is used to save the data of mysql dump
  13. */
  14. var $ dump;
  15. /**
  16. * @var is used for database result data and insert instructions
  17. */
  18. var $struktur = array();
  19. /**
  20. * @var compressed file name zip
  21. */
  22. var $datei;
  23. /**
  24. * Structural function
  25. * Connect to database
  26. * @return
  27. */
  28. public function Backup ($options)
  29. {
  30. //Read configuration from formal parameters
  31. foreach($options AS $name => $value)
  32. {
  33. $this->config[$name] = $value;
  34. }
  35. // Connect to the 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. * Function to execute backup database process
  42. * @return
  43. */
  44. public function backupDB()
  45. {
  46. //Command to start backup
  47. if(isset($_POST['backup']))
  48. {
  49. // Check whether the 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 reading 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 = "nn".$createtable."nn";
  66. array_push($tables, $str);
  67. // Query all data rows in the 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 data and convert it into 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. // insert data Put it in the array and remove duplicates
  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 and insert command together
  108. $this->struktur = array_combine($tables, $insert);
  109. // Execute the dump function
  110. $this->createDUMP($this ->struktur);
  111. // Generate zip archive
  112. $this->createZIP();
  113. /**End of backup **/
  114. // Send an email to the specified email address, the attachment contains the sql backup , if you set it ^_^
  115. if(isset($this->config['email']) && !empty($this->config['email']))
  116. {
  117. $this-> ;sendEmail();
  118. }
  119. // output
  120. echo '

    Backup completed

    Download backup


  121. ';
  122. }
  123. }
  124. /**
  125. * Send email function
  126. * @return
  127. */
  128. protected function sendEmail()
  129. {
  130. // Read email address
  131. foreach($this->config['email'] AS $email)
  132. {
  133. $to = $email;
  134. $from = $this->config['email' ][0];
  135. $message_body = "The zip package contained in this email is a database backup";
  136. $msep = strtoupper (md5 (uniqid (time ())));
  137. // Set email header
  138. $header =
  139. "From: $fromrn" .
  140. "MIME-Version: 1.0rn" .
  141. "Content-Type: multipart/mixed; boundary=".$msep."rnrn" .
  142. "--$mseprn" .
  143. "Content-Type: text/plainrn" .
  144. "Content-Transfer-Encoding: 8bitrnrn" .
  145. $message_body . "rn";
  146. // File name
  147. $dateiname = $this->datei;
  148. / / Compressed package size
  149. $dateigroesse = filesize ($dateiname);
  150. // Read compressed package
  151. $f = fopen ($dateiname, "r");
  152. // Save to attachment
  153. $attached_file = fread ($f , $dateigroesse);
  154. // Close the compressed package
  155. fclose ($f);
  156. // Create an attachment
  157. $attachment = chunk_split (base64_encode ($attached_file));
  158. // Set the attachment header
  159. $header .=
  160. "--" . $msep . "rn" .
  161. "Content-Type: application/zip; name='Backup'rn" .
  162. "Content-Transfer-Encoding: base64rn" .
  163. "Content-Disposition: attachment; filename ='Backup.zip'rn" .
  164. "Content-Description: Mysql Datenbank Backup im Anhangrnrn" .
  165. $attachment . "rn";
  166. // Mark attachment end unknown
  167. $header .= "--$msep-- ";
  168. // Email title
  169. $subject = "Database Backup";
  170. // Sending emails requires enabling PHP support ^^
  171. if(mail($to, $subject, '', $header) == FALSE)
  172. {
  173. die("Unable to send email, please check your email address");
  174. }
  175. echo "

    Email sent successfully

    ";
  176. }
  177. }
  178. /**
  179. * Create a compressed package of database backup and save it to the specified directory on the server
  180. * @return
  181. */
  182. protected function createZIP()
  183. {
  184. // Folder permissions must be sufficient
  185. chmod($this->config['folder'], 0777);
  186. // Create Compressed package
  187. $zip = new ZipArchive();
  188. //Set the compressed package file name
  189. $this->datei = $this->config['folder'].$this->config['mysql'] [3]."_"
  190. .date("j_F_Y_g_i_a").".zip";
  191. // See if the compressed package can be opened
  192. if ($zip->open($this->datei, ZIPARCHIVE ::CREATE)!==TRUE) {
  193. exit("Cannot open<".$this->datei.">n");
  194. }
  195. // Put the dumped data into the compressed package
  196. $zip->addFromString("dump.sql", $this->dump);
  197. // Close the compressed package
  198. $zip->close();
  199. // Check whether the compressed package is generated
  200. if(!file_exists($this->datei))
  201. {
  202. die("Unable to generate compressed package");
  203. }
  204. echo "

    Database backup compressed 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 = << -- 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. * Generate interface function for selecting data table
  231. * @return
  232. */
  233. public function outputForm()
  234. {
  235. / / Select all
  236. $result = mysql_list_tables($this->config['mysql'][3]);
  237. $buffer = '
  238. Select the data table that needs to be backed up


  239. < ;/form>
  240. ';
  241. echo $buffer;
  242. }
  243. }
  244. ?>
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template