Mysql database backup and restore under Linux

1. Database list display

First of all, it is necessary to find the database file, obtain the file information, and display it in the form of a list:

$backup_path = 'www/wwwroot/database'; //包含数据库文件夹地址
$file = self::scandirFolder($backup_path);
$list=[];
if(!empty($file)){
    foreach($file as $k=>$v){
        $list[$k]['file_name']=$v;
        $res = get_headers(http() . '/backup/database/'.$v,true);
        //四舍五入获取文件大小,单位M;
        $list[$k]['file_size']=round($res['Content-Length']/1024/1024,2);
    }
}
/**
 * @param $dir
 * @param array $filter
 * @return array
 * 获取目录下目录
 */
function scandirFolder($path)
{
    $list     = [];
    $temp_list = scandir($path);
    foreach ($temp_list as $file)
    {
        //排除根目录
        if ($file != ".." && $file != ".")
        {
            if (is_dir($path . "/" . $file))
            {
                //子文件夹,进行递归
                $list[$file] = self::scandirFolder($path . "/" . $file);
            }
            else
            {
                //根目录下的文件
                $list[] = $file;
            }
        }
    }
    return $list;
}
/**
 * @param $dir /目录
 * @param string $ext 指定文件
 * @return array
 * 获取目录下文件
 */
public function getDirFile($dir, $ext = 'php', $del_ext = false)
{
    $res = scandir($dir);
    foreach ($res as $k => $dir_path) {
        if (!is_file($dir . DIRECTORY_SEPARATOR . $dir_path)) {
            unset($res[$k]);
        } else {
            if (!empty($ext) && pathinfo($dir_path, 4) !== $ext) {
                unset($res[$k]);
            }
            if ($del_ext) {
                $res[$k] = str_replace('.' . pathinfo($dir_path, 4), '', $dir_path);
            }
        }

    }
    rsort($res);
    return $res;
}

In this way, the list of database files is obtained, and the output is displayed on the foreground.

2. Data backup

//设置时区
 date_default_timezone_set("Asia/Shanghai");
 /*********************************备份数据库start*********数据库大小100G以下*******************/
                $db_user='';//数据库账号
                $db_pwd='';//数据库密码
                $db_name='';//数据库名
                //固定格式
                $filename='db_'.$database['database'].'_'. date("Ymd")."_".date("His");
                $name=根路径.'database' . DIRECTORY_SEPARATOR.$filename. '.sql.gz';//数据库文件存储路径
                //已压缩包的形式备份
                $exec="/www/server/mysql/bin/mysqldump -u".$db_user." -p".$db_pwd." ".$db_name." | gzip > ".$name;
                $result=exec($exec);//注意 php要放开禁用函数exec

3. Database restore

/*********************************还原数据库start******数据库大小100G以下**********************/
$db_user='';//数据库账号
$db_pwd='';//数据库密码
$db_name='';//数据库名
$filename=$param_name;
$name=根路径 . 'database' . DIRECTORY_SEPARATOR.$filename;//数据库文件存储路径
//先解压,再还原
$exec="gunzip < ".$name." |/www/server/mysql/bin/mysql  -u".$db_user." -p".$db_pwd." ".$db_name." >/dev/null  &";
$result=exec($exec);

Guess you like

Origin blog.csdn.net/echozly/article/details/122235534