Php database backup class sharing a good php database backup class

Source: Internet
Author: User
Tags php database ziparchive
Php database backup class sharing a good php database backup class

  1. Error_reporting (0); // php alarm prompt for eliminating all evil
  2. // Set the 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 the backup command
  8. If (isset ($ _ POST ['backup '])
  9. {
  10. // Start backup
  11. $ B-> backupDB ();
  12. }
  13. // Display the backup table
  14. $ B-> outputForm ();
  15. ?>

Php database backup implementation code:

  1. /**
  2. * Back up a 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 mysql dump data.
  13. */
  14. Var $ dump;
  15. /**
  16. * @ Var is used for database result data and insert commands.
  17. */
  18. Var $ struktur = array ();
  19. /**
  20. * @ Var compression file name zip
  21. */
  22. Var $ datei;
  23. /**
  24. * Structure functions
  25. * Connect to the database
  26. * @ Return
  27. */
  28. Public function Backup ($ options)
  29. {
  30. // Read the configuration from the parameter
  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. * Functions used to execute the database backup process
  42. * @ Return
  43. */
  44. Public function backupDB ()
  45. {
  46. // Backup start Command
  47. If (isset ($ _ POST ['backup '])
  48. {
  49. // Check whether a data table is selected
  50. If (empty ($ _ POST ['table'])
  51. {
  52. Die ("Select a data table. ");
  53. }
  54. /** Start backup **/
  55. $ Tables = array ();
  56. $ Insert = array ();
  57. $ SQL _statement = '';
  58. // Lock the database to be backed up to prevent dirty data reading
  59. Foreach ($ _ POST ['table'] AS $ table)
  60. {
  61. Mysql_query ("lock table $ table WRITE ");
  62. // Obtain 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. // Query 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 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, removing 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 together with the insert command
  108. $ This-> struktur = array_combine ($ tables, $ insert );
  109. // Execute the dump function
  110. $ This-> createDUMP ($ this-> struktur );
  111. // Generate a zip package
  112. $ This-> createZIP ();
  113. /** End backup **/
  114. // Send an email to the specified email address. the attachment contains SQL Backup. if you have set it, ^_^
  115. If (isset ($ this-> config ['email ']) &! Empty ($ this-> config ['email '])
  116. {
  117. $ This-> sendEmail ();
  118. }
  119. // Output
  120. Echo 'backup complete $ this-> datei. '"> Download backup


  121. ';
  122. }
  123. }
  124. /**
  125. * Email sending function
  126. * @ Return
  127. */
  128. Protected function sendEmail ()
  129. {
  130. // Read the 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 the 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 ".
  142. "-- $ Msep \ r \ n ".
  143. "Content-Type: text/plain \ r \ n ".
  144. "Content-Transfer-Encoding: 8bit \ r \ n ".
  145. $ Message_body. "\ r \ n ";
  146. // File name
  147. $ Dateiname = $ this-> datei;
  148. // Size of the compressed package
  149. $ Dateigroesse = filesize ($ dateiname );
  150. // Read the compressed package
  151. $ F = fopen ($ dateiname, "r ");
  152. // Save it to the 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. "\ 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 ".
  165. $ Attachment. "\ r \ n ";
  166. // Mark the end of the attachment as unknown
  167. $ Header. = "-- $ msep --";
  168. // Mail title
  169. $ Subject = "database backup ";
  170. // Php support must be enabled for sending emails ^
  171. If (mail ($ to, $ subject, '', $ header) = FALSE)
  172. {
  173. Die ("unable to send mail, please check the email address ");
  174. }
  175. Echo"

    Email sent successfully

    ";
  176. }
  177. }
  178. /**
  179. * Create a Compressed database backup package and save it to the specified directory on the server.
  180. * @ Return
  181. */
  182. Protected function createZIP ()
  183. {
  184. // You must have sufficient folder permissions.
  185. Chmod ($ this-> config ['Folder'], 0777 );
  186. // Create a 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. // Check whether 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 dump data in 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"

    The database backup package is 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 ");
  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 functions for selecting data tables
  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 to be backed up
  239. ';
  240. Echo $ buffer;
  241. }
  242. }
  243. ?>

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.