首頁 >後端開發 >php教程 >用php實作備份資料庫ZIP及匯出

用php實作備份資料庫ZIP及匯出

巴扎黑
巴扎黑原創
2016-11-23 14:01:151071瀏覽

 经常在有的PHP开源系统中,看到有备份数据库并导出的方法,其实代码不复杂,下面 
大概讲解下,以WINDOWS为例子,两类方法,一个是目录文件夹要有执行脚本权限的, 
一个个是没有权限的,代码如下: 

一) 

<?php   
    
$username = "root";    
$password = "";    
$hostname = "localhost";    
$dbname   = "test";   
    
  
$dumpfname = $dbname . "_" . date("Y-m-d_H-i-s").".sql";   
$command = "C:\\xampp\\mysql\\bin\\mysqldump --add-drop-table --host=$hostname   
    --user=$username ";   
if ($password)    
        $command.= "--password=". $password ." ";    
$command.= $dbname;   
$command.= " > " . $dumpfname;   
system($command);   
    
// zip 数据文件  
$zipfname = $dbname . "_" . date("Y-m-d_H-i-s").".zip";   
$zip = new ZipArchive();   
if($zip->open($zipfname,ZIPARCHIVE::CREATE))    
{   
   $zip->addFile($dumpfname,$dumpfname);   
   $zip->close();   
}   
    
// read zip file and send it to standard output   
if (file_exists($zipfname)) {   
    header(&#39;Content-Description: File Transfer&#39;);   
    header(&#39;Content-Type: application/octet-stream&#39;);   
    header(&#39;Content-Disposition: attachment; filename=&#39;.basename($zipfname));   
    flush();   
    readfile($zipfname);   
    exit;   
}   
?>



方法2 文件夹没相关权限 

<?php   
ob_start();   
    
$username = "root";    
$password = "";    
$hostname = "localhost";    
$dbname   = "test";   
    
$command = "C:\\xampp\\mysql\\bin\\mysqldump --add-drop-table --host=$hostname   
    --user=$username ";   
if ($password)    
        $command.= "--password=". $password ." ";    
$command.= $dbname;   
system($command);   
    
$dump = ob_get_contents();    
ob_end_clean();   
    
  
//不ZIP了  
header(&#39;Content-Description: File Transfer&#39;);   
header(&#39;Content-Type: application/octet-stream&#39;);   
header(&#39;Content-Disposition: attachment; filename=&#39;.basename($dbname . "_" .    
    date("Y-m-d_H-i-s").".sql"));   
flush();   
echo $dump;   
exit();]]>   
?>


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:php遍歷對象下一篇:php遍歷對象