二款phpDatabase Backup類程式碼_PHP教程

來源:互聯網
上載者:User
小生今天沒事收集了兩款phpDatabase Backup程式,這裡可以完成功能有:1.備份指定資料表、2.打包成zip檔案、3.發送到指定郵箱地址,準系統就這些了

下面看下使用方法:

代碼如下 複製代碼

error_reporting(0);//消滅萬惡的php警示提示
//設定郵箱
$options = array('email' => array('email1', 'email2'),
'folder' => './backup/',
'mysql' => array('localhost', 'user', 'password', 'db'));

$b = new Backup($options);

// 提交備份命令
if(isset($_POST['backup']))
{
// 開始備份
$b->backupDB();
}
// 顯示備份表
$b->outputForm();
?>

具體類實現:

代碼如下 複製代碼


class Backup
{
/**
* @var 用於儲存配置參數
*/
var $config;

/**
* @var 用於儲存mysql dump的資料
*/
var $dump;

/**
* @var 用於資料庫結果資料以及insert指令
*/
var $struktur = array();

/**
* @var 壓縮檔名zip
*/
var $datei;

/**
* 結構函數
* 串連資料庫
* @return
*/
public function Backup($options)
{
// 從形參中讀取配置
foreach($options AS $name => $value)
{
$this->config[$name] = $value;
}

// 串連資料庫
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());
}

/**
* 執行備份資料庫流程的函數
* @return
*/
public function backupDB()
{
// 開始備份的命令
if(isset($_POST['backup']))
{
// 檢測是否選擇了資料表
if(empty($_POST['table']))
{
die("請選擇一個資料表。");
}

/** 開始備份 **/
$tables = array();
$insert = array();
$sql_statement = '';

// 鎖定需要備份的資料庫,防止讀髒資料
foreach($_POST['table'] AS $table)
{
mysql_query("LOCK TABLE $table WRITE");

// 擷取資料庫結構
$res = mysql_query('SHOW CREATE TABLE '.$table.'');
$createtable = mysql_result($res, 0, 1);
$str = "nn".$createtable."nn";

array_push($tables, $str);

// 查詢資料表中的所有資料行
$sql = 'SELECT * FROM '.$table;
$query = mysql_query($sql) or die(mysql_error());
$feld_anzahl = mysql_num_fields($query);

$sql_statement = '--
-- Data Table `$table`
--
';

// 開始讀資料,並將其轉換為insert命令
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";
}

// 將insert資料放在數組中,去重
if(!in_array($sql_statement, $insert))
{
array_push($insert, $sql_statement);
unset($sql_statement);
}

unset($sql_statement);

}

// 將資料庫結構與insert命令放在一起啦
$this->struktur = array_combine($tables, $insert);

// 執行dump函數
$this->createDUMP($this->struktur);

// 產生zip壓縮包
$this->createZIP();

/** 備份結束 **/

// 發一封郵件到指定郵箱,附件包含sql備份,如果你設定了的話^_^
if(isset($this->config['email']) && !empty($this->config['email']))
{
$this->sendEmail();
}

// output
echo '

備份完成啦

$this->datei.'">下載備份



';
}
}

/**
* 發送郵件函數
* @return
*/
protected function sendEmail()
{
// 讀取郵箱地址
foreach($this->config['email'] AS $email)
{
$to = $email;

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

$message_body = "本郵件中包含的zip壓縮包為Database Backup";

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

// 設定email頭
$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";

// 檔案名稱
$dateiname = $this->datei;

// 壓縮包大小
$dateigroesse = filesize ($dateiname);

// 讀取壓縮包
$f = fopen ($dateiname, "r");
// 儲存到附件
$attached_file = fread ($f, $dateigroesse);
// 關閉壓縮包
fclose ($f);
// 建立一個附件
$attachment = chunk_split (base64_encode ($attached_file));

// 設定附件頭
$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";

// 標記附件結束未知
$header .= "--$msep--";

// 郵件標題
$subject = "Database Backup";

// 發送郵件需要開啟php相應支援哦^^
if(mail($to, $subject, '', $header) == FALSE)
{
die("無法發送郵件,請檢查郵箱地址");
}

echo "

郵件發送成功

";
}
}

/**
* 建立Database Backup的壓縮包並儲存到伺服器指定目錄中
* @return
*/
protected function createZIP()
{

// 檔案夾許可權要夠
chmod($this->config['folder'], 0777);

// 建立壓縮包
$zip = new ZipArchive();
// 設定壓縮包檔案名稱
$this->datei = $this->config['folder'].$this->config['mysql'][3]."_"
.date("j_F_Y_g_i_a").".zip";

// 看看壓縮包能不能開啟
if ($zip->open($this->datei, ZIPARCHIVE::CREATE)!==TRUE) {
exit("無法開啟 <".$this->datei.">n");
}

// 把dump出來的資料放到壓縮包裡
$zip->addFromString("dump.sql", $this->dump);
// 關閉壓縮包
$zip->close();

// 看看壓縮包有沒有產生
if(!file_exists($this->datei))
{
die("無法產生壓縮包");
}

echo "

Database Backup壓縮包成功產生

";
}

/**
* mysql dump函數
* @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;
}

/**
* 產生選擇資料表的介面函數
* @return
*/
public function outputForm()
{
// 選擇全部
$result = mysql_list_tables($this->config['mysql'][3]);

$buffer = '

選擇需要備份的資料表

';

echo $buffer;
}
}

?>

通用Database Backup類

代碼如下 複製代碼

/*Database Backup:NOTICE:此類要添加資料庫連接才能正常工作*/
Class Back_up_databaseextendsdbstuff{
//類開始
var $HOST;
var $USERNAME;
var $PASSWORD;
var $DATABASE;
function Back_up_database($host,$username,$password,$database){
//初始化資料庫連接
$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;
}
//取得資料庫中的表
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;
}
//取得每個表中的FIELDS和屬性並產生CREATETABLE語句
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;
}
//取得表中的資料並產生ISERTINTO語句
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;
}
//擷取所有資料並串連成新的字串並將它寫入檔案中.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\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;
}
//寫入一個檔案
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();
?>

http://www.bkjia.com/PHPjc/630701.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/630701.htmlTechArticle小生今天沒事收集了兩款phpDatabase Backup程式,這裡可以完成功能有:1.備份指定資料表、2.打包成zip檔案、3.發送到指定郵箱地址,準系統就這...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.