当前位置:Gxlcms > 数据库问题 > PHP导出MYSQL数据库并压缩

PHP导出MYSQL数据库并压缩

时间:2021-07-01 10:21:17 帮助过:2人阅读

$username = "root";//你的MYSQL用户名 $password = "";//密码 $hostname = "localhost";//MYSQL服务器地址 $dbname = "cars";//数据库名 $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(); } if (file_exists($zipfname)) { header(‘Content-Description: File Transfer‘); header(‘Content-Type: application/octet-stream‘); header(‘Content-Disposition: attachment; filename=‘.basename($zipfname)); flush(); readfile($zipfname); exit; } ?>

上述代码可保存成一个PHP文件,如mysqlbak.php,注意,此文件必须有写权限。为了使用方便,你可以在后台给此文件一个链接,需要导出MYSQL时,你只需点击一下就执行备份导出操作。

第二种方法:不需要写权限,但不压缩SQL文件,代码如下:

<?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();
header(‘Content-Description: File Transfer‘);
header(‘Content-Type: application/octet-stream‘);
header(‘Content-Disposition: attachment; filename=‘.basename($dbname . "_" . date("Y-m-d_H-i-s").".sql"));
flush();
echo $dump;
exit();
?>

两种方法你可以选用一种,同样可将第二种方法保存成mysqlbak.php文件,在后台给个链接,用着方便。

PHP导出MYSQL数据库并压缩

标签:

人气教程排行