Two php database backup program code _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Tags ziparchive
Two php database backup program codes. John has nothing to do with collecting two php database backup programs today. The following functions can be completed: 1. backup specified data table, 2. package it into a zip file, 3. sent to the specified email address. The basic functions are nothing to collect today. two php database backup programs can be completed here: 1. backup specified data table, 2. package it into a zip file, 3. send to the specified email address. this is the basic function.

The usage is as follows:

The code is as follows:

Error_reporting (0); // php alarm prompt for eliminating all evil
// Set the email address
$ Options = array ('email '=> array ('email1', 'email2 '),
'Folder' => './backup /',
'Mysql' => array ('localhost', 'user', 'password', 'DB '));

$ B = new Backup ($ options );

// Submit the backup command
If (isset ($ _ POST ['backup '])
{
// Start backup
$ B-> backupDB ();
}
// Display the backup table
$ B-> outputForm ();
?>

Class implementation:

The code is as follows:


Class Backup
{
/**
* @ Var is used to save configuration parameters.
*/
Var $ config;

/**
* @ Var is used to save mysql dump data.
*/
Var $ dump;

/**
* @ Var is used for database result data and insert commands.
*/
Var $ struktur = array ();

/**
* @ Var compression file name zip
*/
Var $ datei;

/**
* Structure functions
* Connect to the database
* @ Return
*/
Public function Backup ($ options)
{
// Read the configuration from the parameter
Foreach ($ options AS $ name => $ value)
{
$ This-> config [$ name] = $ value;
}

// Connect to the database
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 ());
}

/**
* Functions used to execute the database backup process
* @ Return
*/
Public function backupDB ()
{
// Backup start Command
If (isset ($ _ POST ['backup '])
{
// Check whether a data table is selected
If (empty ($ _ POST ['table'])
{
Die ("Select a data table. ");
}

/** Start backup **/
$ Tables = array ();
$ Insert = array ();
$ SQL _statement = '';

// Lock the database to be backed up to prevent dirty data reading
Foreach ($ _ POST ['table'] AS $ table)
{
Mysql_query ("lock table $ table WRITE ");

// Obtain the database structure
$ Res = mysql_query ('Show CREATE Table'. $ TABLE .'');
$ Createtable = mysql_result ($ res, 0, 1 );
$ Str = "nn". $ createtable. "nn ";

Array_push ($ tables, $ str );

// Query all data rows in a data table
$ SQL = 'select * from'. $ table;
$ Query = mysql_query ($ SQL) or die (mysql_error ());
$ Feld_anzahl = mysql_num_fields ($ query );

$ SQL _statement = '--
-- Data Table '$ table'
--
';

// Start reading data and convert it to the insert command
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 (empty ($ ds-> $ name )){
$ Ds-> $ name = 'null ';
}
If ($ I ==$ feld_anzahl-1 ){
$ SQL _statement. = '"'. $ ds-> $ name .'"';
} Else {
$ SQL _statement. = '"'. $ ds-> $ name .'",';
}
}
$ SQL _statement. = "); n ";
}

// Put the insert data in the array, removing duplicates
If (! In_array ($ SQL _statement, $ insert ))
{
Array_push ($ insert, $ SQL _statement );
Unset ($ SQL _statement );
}

Unset ($ SQL _statement );

}

// Put the database structure together with the insert command
$ This-> struktur = array_combine ($ tables, $ insert );

// Execute the dump function
$ This-> createDUMP ($ this-> struktur );

// Generate a zip package
$ This-> createZIP ();

/** End backup **/

// Send an email to the specified email address. the attachment contains SQL Backup. if you have set it, ^_^
If (isset ($ this-> config ['email ']) &! Empty ($ this-> config ['email '])
{
$ This-> sendEmail ();
}

// Output
Echo 'backup complete $ this-> datei. '"> Download backup



';
}
}

/**
* Email sending function
* @ Return
*/
Protected function sendEmail ()
{
// Read the email address
Foreach ($ this-> config ['email '] AS $ email)
{
$ To = $ email;

$ From = $ this-> config ['email '] [0];

$ Message_body = "The zip package contained in this email is a database backup ";

$ Msep = strtoupper (md5 (uniqid (time ())));

// Set the email header
$ Header =
"From: $ fromrn ".
"MIME-Version: 1.0rn ".
"Content-Type: multipart/mixed; boundary =". $ msep. "rnrn ".
"-- $ Mseprn ".
"Content-Type: text/plainrn ".
"Content-Transfer-Encoding: 8 bitrnrn ".
$ Message_body. "rn ";

// File name
$ Dateiname = $ this-> datei;

// Size of the compressed package
$ Dateigroesse = filesize ($ dateiname );

// Read the compressed package
$ F = fopen ($ dateiname, "r ");
// Save it to the attachment
$ Attached_file = fread ($ f, $ dateigroesse );
// Close the compressed package
Fclose ($ f );
// Create an attachment
$ Attachment = chunk_split (base64_encode ($ attached_file ));

// Set the attachment header
$ 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 ";

// Mark the end of the attachment as unknown
$ Header. = "-- $ msep --";

// Mail title
$ Subject = "database backup ";

// Php support must be enabled for sending emails ^
If (mail ($ to, $ subject, '', $ header) = FALSE)
{
Die ("unable to send mail, please check the email address ");
}

Echo"

Email sent successfully

";
}
}

/**
* Create a Compressed database backup package and save it to the specified directory on the server.
* @ Return
*/
Protected function createZIP ()
{

// You must have sufficient folder permissions.
Chmod ($ this-> config ['Folder'], 0777 );

// Create a compressed package
$ Zip = new ZipArchive ();
// Set the compressed package file name
$ This-> datei = $ this-> config ['Folder']. $ this-> config ['mysql'] [3]. "_"
. Date ("j_F_Y_g_ I _a"). ". zip ";

// Check whether the compressed package can be opened
If ($ zip-> open ($ this-> datei, ZIPARCHIVE: CREATE )! = TRUE ){
Exit ("cannot open <". $ this-> datei. "> n ");
}

// Put the dump data in the compressed package
$ Zip-> addFromString ("dump. SQL", $ this-> dump );
// Close the compressed package
$ Zip-> close ();

// Check whether the compressed package is generated
If (! File_exists ($ this-> datei ))
{
Die ("unable to generate compressed package ");
}

Echo"

The database backup package is successfully generated.

";
}

/**
* Mysql dump function
* @ Param object $ dump
* @ Return
*/
Protected function createDUMP ($ dump)
{
$ Date = date ("F j, Y, g: I ");

$ 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;
}

/**
* Generate interface functions for selecting data tables
* @ Return
*/
Public function outputForm ()
{
// Select All
$ Result = mysql_list_tables ($ this-> config ['mysql'] [3]);

$ Buffer ='

Select the data table to be backed up

';

Echo $ buffer;
}
}

?>

General database backup

The code is as follows:

/* Database backup: NOTICE: This class can work normally only when a database connection is added */
Class Back_up_databaseextendsdbstuff {
// Starts the class
Var $ HOST;
Var $ USERNAME;
Var $ PASSWORD;
Var $ DATABASE;
Function Back_up_database ($ host, $ username, $ password, $ database ){
// Initialize the database connection
$ 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;
}
// Obtain the table in the database
Function get_table_name ($ database ){
$ This-> Connection;
$ Result = mysql_list_tables ($ database );
$ I = 0;
While ($ I $ 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;
}
// Obtain FIELDS and attributes in each table and generate the CREATETABLE statement
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 ";
$ This-> $ table_name = $ tabledump;
Return $ this-> $ table_name;
}
// Obtain the data in the table and generate the ISERTINTO statement
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;
}
// Obtain all the data, connect it to a new string, and write it into the file. 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.bKjia. c0m \ n ".
"# PleasevisitourwebsitefornewestinfomationaboutAntsnet_Web_Studio! \ N ".
"# -------------------------------------------------------- \ N ";
$ Table_name = $ this-> get_table_name ($ database_name );
$ Array_table = explode (",", $ table_name );
For ($ I = 0; $ 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;
}
// Write a file
Function write_file ($ file_path, $ file_contents ){
If (@! $ Fp = fopen ($ file_path, 'w ')){
$ Status = "ThisFileCouldNotOpenOrRead .";
} Else {
Flock ($ fp, 3 );
Fwrite ($ fp, $ file_contents );
Fclose ($ fp );
Window. google_render_ad ();
?>

...

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.