之前有一个需求是要在开发环境写一个手动备份数据库的脚本,所以就有了这个东西
主要为两个文件,一个脚本文件,一个配置文件
脚本文件内容如下:
<?php
date_default_timezone_set('PRC');
$config = require __DIR__."/conf.php";
/*
* 数据库备份
*/
$backup_path = __DIR__."/backup/";
if (!is_dir($backup_path)){
mkdir(__DIR__."/backup/");
}
foreach($config as $k=>$v){
if (!is_dir(__DIR__."/backup/".$v['host']."_".$v['database'])){
mkdir(__DIR__."/backup/".$v['host']."_".$v['database']);
}
$cmd = "mysqldump -h".$v['host']." -u".$v['user']." -p".$v['pass']." ".$v['database']." > ".__DIR__."/backup/".$v['host']."_".$v['database']."/".date('Ymd',time()).'__'.time().".sql";
exec($cmd,$array,$int);
echo $v['host']."_".$v['database']." is backuped!".PHP_EOL;
}
/*
* 删除历史备份
*/
$databases = scandir($backup_path);
foreach($databases as $database){
$database_path = $backup_path.DIRECTORY_SEPARATOR.$database;
if ($database === '.' || $database ==='..' || !is_dir($database_path)){
continue;
}
$versions = scandir($database_path);
$files = [];
foreach($versions as $key => $version){
$file_path = $database_path.DIRECTORY_SEPARATOR.$version;
if ($database === '.' || $database ==='..' || !is_file($file_path)){
continue;
}
list($name,$time) = explode('__',str_replace('.sql','',$version));
$files[$time] = $file_path;
}
if (count($files)>2){
ksort($files,SORT_NUMERIC);
reset($files);
unlink(current($files));
echo current($files)." is deleted!".PHP_EOL;
}
}
还有一个由二维数组组成的配置文件:
<?php
return [
[
'host' => '***.***.***.***',
'user' => 'root',
'pass' => 'root',
'database' => 'test'
],
[
'host' => '***.***.***.***',
'user' => 'root',
'pass' => 'root',
'database' => 'test2'
]
];
然后将文件和mysqldump程序放到同个目录,执行脚本后,就会生成备份文件并保存在当前目录下的backup目录
本文为原创文章,转载无需和本人联系,但请注明来自 飞行猿博客 https://www.hzfblog.com
最新评论