Two PHP database backup class program code

Source: Internet
Author: User
Tags foreach pack php database zip ziparchive set up email

Here's how to use it:

The code is as follows Copy Code

<?php
error_reporting (0);//Eliminate all evils of PHP alert hints
Set mailbox
$options = Array (' Email ' => Array (' Email1 ', ' email2 '),
' Folder ' => './backup/',
' MySQL ' => array (' localhost ', ' user ', ' password ', ' db '));

$b = new Backup ($options);

Submit a backup command
if (isset ($_post[' backup '))
{
Start Backup
$b->backupdb ();
}
Show Backup Table
$b->outputform ();
?>

Specific class implementation:

The code is as follows Copy Code

<?php

Class Backup
{
/**
* @var to save configuration parameters
*/
var $config;

/**
* @var data to save MySQL dump
*/
var $dump;

/**
* @var for database result data and insert instructions
*/
var $struktur = array ();

/**
* @var Compressed file name zip
*/
var $datei;

/**
* Structure function
* Connect to the database
* @return
*/
Public Function Backup ($options)
{
Reading configuration from formal parameters
foreach ($options as $name => $value)
{
$this->config[$name] = $value;
}

Connecting to a 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 that perform the backup database process
* @return
*/
Public Function backupdb ()
{
command to start Backup
if (isset ($_post[' backup '))
{
Detects whether a datasheet is selected
if (Empty ($_post[' table '))
{
Die ("Please select a datasheet.") ");
}

/** Start Backup **/
$tables = Array ();
$insert = Array ();
$sql _statement = ';

Lock the database that needs to be backed up to prevent dirty data from being read
foreach ($_post[' table '] as $table)
{
mysql_query ("LOCK TABLE $table WRITE");

Getting the database structure
$res = mysql_query (' Show CREATE TABLE '. $table. ');
$createtable = mysql_result ($res, 0, 1);
$str = "nn". $createtable. " nn ";

Array_push ($tables, $STR);

Querying all rows of data in a datasheet
$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 the 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";
}

Place the insert data in an array to
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 Dump function
$this->createdump ($this->struktur);

To generate a ZIP compression package
$this->createzip ();

/** Backup End **/

Send a message to the specified mailbox, the attachment contains the SQL backup, if you set the words ^_^
if (isset ($this->config[' email ')) &&!empty ($this->config[' email '))
{
$this->sendemail ();
}

Output
Echo '

$this->datei. ' " > Download Backup </a>
<br/>
<br/> ';
}
}

/**
* Send mail function
* @return
*/
protected function SendEmail ()
{
Read Mailbox Address
foreach ($this->config[' email '] as $email)
{
$to = $email;

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

$message _body = "The ZIP compression package contained in this message is a database backup";

$MSEP = Strtoupper (MD5 (UNIQID (time)));

Set up email headers
$header =
"From: $fromrn".
"Mime-version:1.0rn".
"Content-type:multipart/mixed; Boundary= ". $msep." Rnrn ".
"--$mseprn".
"Content-type:text/plainrn".
"Content-transfer-encoding:8bitrnrn".
$message _body. "RN";

Filename
$dateiname = $this->datei;

Compressed package size
$dateigroesse = FileSize ($dateiname);

Reading a compressed package
$f = fopen ($dateiname, "R");
Save to Attachment
$attached _file = fread ($f, $dateigroesse);
Turn off compression packs
Fclose ($f);
Create an attachment
$attachment = Chunk_split (Base64_encode ($attached _file));

Set up Attachment headers
$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";

Tag Attachment End Unknown
$header. = "-$msep-";

Message headers
$subject = "Database Backup";

Send mail need to open the corresponding support PHP Oh ^ ^
if (Mail ($to, $subject, ', $header) = = FALSE)
{
Die ("Unable to send mail, please check email address");
}

echo "<p><small> send success </small></p> message";
}
}

/**
* Set up a compression package for the database backup and save it to the server specified directory
* @return
*/
protected function Createzip ()
{

folder permissions are sufficient
chmod ($this->config[' folder '], 0777);

Create a compressed package
$zip = new Ziparchive ();
Set cabinet file name
$this->datei = $this->config[' folder '. $this->config[' MySQL '][3]. " _"
. Date ("J_f_y_g_i_a"). ". Zip ";

See if the compression pack can be turned on.
if ($zip->open ($this->datei, ziparchive::create)!==true) {
Exit ("Cannot open <". $this->datei. " >n ");
}

Put the dump data in the zip bag.
$zip->addfromstring ("Dump.sql", $this->dump);
Turn off compression packs
$zip->close ();

See if the compression pack has been generated
if (!file_exists ($this->datei))
{
Die ("Unable to generate a compressed package");
}

echo "<p><small> database backup compression package successfully generated </small></p>";
}

/**
* MySQL dump function
* @param object $dump
* @return
*/
protected function Createdump ($dump)
{
$date = Date ("F J, Y, g:i a");

$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 the interface function of the selection datasheet
* @return
*/
Public Function Outputform ()
{
Select All
$result = mysql_list_tables ($this->config[' MySQL '][3]);

$buffer = '
<fieldset>
<legend> Select the data table you want to back up </legend>
<form method= "POST" action= "" >
<select name= "table[]" multiple= "multiple" size= ">";
while ($row = Mysql_fetch_row ($result))
{
$buffer. = ' <option value= '. $row [0]. ' " > '. $row [0]. ' </option> ';
}
$buffer. = ' </select>
<br/><br/>
<input type= "Submit" Name= "Backup" value= "Backing Up selected data table"/>
</form>
</fieldset> ';

Echo $buffer;
}
}

?>

Common Database Backup classes

The code is as follows Copy Code

<?php
/* Database backup: NOTICE: This class to add a database connection to work properly.
Class back_up_databaseextendsdbstuff{
Class starts
var $HOST;
var $USERNAME;
var $PASSWORD;
var $DATABASE;
function Back_up_database ($host, $username, $password, $database) {
Initializing a 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;
}
To get a table in a database
function Get_table_name ($database) {
$this->connection;
$result =mysql_list_tables ($database);
$i = 0;
while ($i <mysql_num_rows ($result)) {
$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;
}
Get the fields and attributes from each table and generate CreateTable statements
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\n ";
$this-> $table _name= $tabledump;
Return$this-> $table _name;
}
Get the data from 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;
}
Gets all the data and joins it into the new string and writes it to 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.111cn.net \ n ".
"#PleasevisitourwebsitefornewestinfomationaboutAntsnet_Web_Studio!\n".
"#--------------------------------------------------------\n\n\n";
$table _name= $this->get_table_name ($database _name);
$array _table=explode (",", $table _name);
For ($i =0 $i <count ($array _table); $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 = "<fontcolor=\" red\ ">ThisFileCouldNotOpenOrRead.</font>";
}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.