您的位置:首页 > 运维架构 > 网站架构

windows PHP写的自动备份网站和MYSQL数据

2016-03-21 11:08 706 查看
<?php
/***********************************************
web_backup.php
************************************************
说明
@author 杨军平
@date 2007年10月
针对目前我中心需要承担网站维护工作,
但是手工备份及其繁琐效率不高,因此
在前人的基础上进行了扩展,实现自动备份
**************************************************
用法
我的php及mysql安装目录为D:\phpstudy\php5
D:\phpstudy\php5\mysql
在D:\phpstudy\php5
新建目录winrar,拷贝C:\program files\winrar
中winrar.exe 和Rarreg.key到新建的winrar目录中

在D:\phpstudy\php5 中新建webback.bat文件内容如下
**************************************************
@echo off
php.exe web_backup.php
if exist webback_temp.bat call webback_temp.bat
ftp -i -s:ftp.src
***************************************************
在windows中新建计划任务定时调用webback.bat
***************************************************/
//ftp配置文件
$host='111.222.111.222';
$username="jszx";
$password="jszxpass";
$dest="112";
//数据库配置
$db_username = "root";
$db_password = "weoffice";
//保存目录,路径要用反斜杠.您需要手动建立它.
$store_folder = 'E:\mysql_back_day_by_day';
//网站目录
//$olddir='d:\cache';

$time=time();
$mysqldir= "$store_folder\\"."mysql".date("Ymd",$time)."";
//$webdir = "$store_folder\\"."web".date("Ymd",$time)."";
//if(file_exists("$webdir.rar")) die("File exists.\r\n");
if(file_exists("$mysqldir")) die("File exists.\r\n");
//创建mysql备份目录
@mkdir($mysqldir);
//生成fpt.src文件 配置ftp 自动上传
$ftpcommand='';
$ftpcommand.="open $host \r\n";
$ftpcommand.="$username \r\n";
$ftpcommand.="$password \r\n";
$ftpcommand.="cd $dest \r\n";
//$ftpcommand.="mput $webdir.rar \r\n";
$ftpcommand.="mput $mysqldir.rar \r\n";
$ftpcommand.="quit \r\n";
$ftpcommand.="del ftp.src";
$fp = fopen('ftp.src','w');
fwrite($fp,$ftpcommand);
fclose($fp);
//创建备份mysql命令
mysql_connect("localhost","$db_username","$db_password");
$query=mysql_list_dbs();
$command = '';
while($result=mysql_fetch_array($query)){
$command .= dirname(__FILE__).'\..\mysql\bin\mysqldump --opt '."$result[Database] -u{$db_username} ".($db_password?"-p{$db_password}":"")." > $mysqldir\\$result[Database].sql \r\n";
$command .= "echo dumping database `$result[Database]`... \r\n";
}

$command .= "echo Winrar loading...\r\n";

//压缩mysql备份
$command .= dirname(__FILE__)."\\WinRAR\\WinRAR.exe a -ep1 -r -o+ -m5 -df \"$mysqldir.rar\" \"$mysqldir\" \r\n";
//压缩web目录
//$command .= dirname(__FILE__)."\\WinRAR\\WinRAR a -r \"$webdir\" \"$olddir\" \r\n";

$command .= "echo OK!\r\n";

$command .= "del webback_temp.bat\r\n";

$fp = fopen('webback_temp.bat','w');
fwrite($fp,$command);
fclose($fp);

//删除 5 天前的文件,当然也可以考虑保留更多天的备份
@unlink("$store_folder\\"."mysql".date("Ymd",$time-86400*5).".rar");
@unlink("$store_folder\\"."web".date("Ymd",$time-86400*5).".rar");

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: