一、实现思路
1、单击备份按钮传递参数到后台,ajax实现:
function backupDatabase(){
var back = 'backupDatabase';
$.ajax({
url:'system_backup.php?do=backupDatabase',
type:'POST',
data:back,
dataType:'json',
beforeSend:function(){
interval=window.setInterval(function(){
var text = $("#backupstate2").html();
if(text.length<){
$("#backupstate2").html('数据库备份中.');
}
var text = $("#backupstate2").html();
if (text.length < ){
$("#backupstate2").html(text + '.');
} else {
$("#backupstate2").html('数据库备份中.');
}
}, );
},
success:function(data){
if(data.msg=='1'){
$("#backupstate2").html('数据备份完成!');
alert('备份成功.点击确定后,请立刻单击下载备份数据库!');
$("#db_url").val(data.url);
window.clearInterval(interval);
}else{
alert(data.msg);
$("#backupstate2").html('');
window.clearInterval(interval);
}
}
});
}
2、后台接受参数后进行数据库备份
header("Content-Type: text/html; charset=utf-8");
require_once('../configs/config.php');
require_once("../models/websurvey/webSurvey.class.php");
SysUser::authIsLogin("../login.php");
$user = new SysUser();
if(!empty($_GET['do'])){
$do = $_GET['do'];
switch($do){
case "backupDatabase":
$data = $_POST['back'];
if('backupDatabase' == $data){
// 设置SQL文件保存文件名
$cfg_dbname = 'asteriskcdrdb';
$filename=date("Ymd",time())."-".$cfg_dbname.".sql";
// 获取当前页面文件路径,SQL文件就导出到指定文件夹内
// $savePath = './Public/upload/DB/';
$savePath = '../upload/DB/';
if(!file_exists($savePath)){
mkdir($savePath,,true);
}
$tmpFile = $savePath.$filename;
fopen($tmpFile, "r");
chmod($tmpFile,);
/* //删除之前备份的数据
$dh=opendir($savePath);
if($dh){
while ($file=readdir($dh)) {
if($file!="." && $file!="..") {
$fullpath=$savePath."/".$file;
if(!is_dir($fullpath)) {
unlink($fullpath);
}
}
}
closedir($dh);
} //删除之前备份的数据*/
// 用MySQLDump命令导出数据库
$dbhost = '***.***.***.***';//主机IP地址
$cfg_dbuser = 'root';//用户名
$cfg_dbpwd = '******';//密码
$bool_dump = exec("mysqldump -h$dbhost -u$cfg_dbuser -p$cfg_dbpwd --default-character-set=utf8 $cfg_dbname > ".$tmpFile);
if( == $bool_dump){
$bool_tar = exec("tar -zcvPf /var/spool/asterisk/monitor/system/backup/db.tar /var/spool/asterisk/monitor/upload/DB/$filename");
if( == $bool_tar){
$arr = json_encode(array('msg'=>,'url'=>$filename));
echo $arr;
}else{
$arr = json_encode(array('msg'=>'备份失败,请联系管理员!'));
echo $arr;
}
}
}
exit;
}
default:
break;
}
}
三、效果图:
1、备份前
2、备份中
3、备份成功
4、下载备份数据库
四、注意
1、注意:不同的框架实现的方式不同,但都是大同小异。
2、注意php的exec()函数,执行成功后的返回值是0。
3、除了exec()外,还有system()、passthru()、shell_exec()、执行运算符:反引号(“)等等,根据自己的需要进行选择。