Linux下crontab+php实现Mysql数据库定时备份

引言

大项目中的数据库备份是必不可少的,否则一旦出现大问题就GG了,虽然本文是讲述利用PHP实现数据库定时备份,但是这并不是好的方案

想要定时备份数据库,最快捷安全的方法就是利用shell脚本了,功能强大操作方便,而且执行速度极快,不像PHP还需要被apache解析一把。。

当然,不管是用php定时备份,还是shell脚本定时备份,都离不开crontab这玩意,毕竟它才是真正的定时器,这里粗略的说一下crontab吧

crontab使用简介

crontab常用基础命令

任务格式 :

* * * * *program分 时 日 月 星期命令

crontab这里就不多说了,有兴趣的可以搜查相关的资料。

当然 ,还有mysql数据库备份的命令

注:-ppassword中间是没有空格的

这里都是些简介,不够详细,但是足够使用了,接下来看代码:

相关代码

DB_config.php

(=> => => 1) ?>

DB_config.php

{= array(‘db_host’ => ‘127.0.0.1’,’db_name’ => ‘ftdtian’,’db_user’ => ‘root’,’db_pwd’ => ‘123’,’db_back_path’ => ‘/home/db_back’,’back_file_suffix’ => ‘bak’,=> 3);;;{//无限制脚本时间set_time_limit(0);//设置时区date_default_timezone_set(‘PRC’););$this->set_config();}{//当前时间$date_format = date(“Y-m-d-H:i:s”,time());$common_shell = “mysqldump -h %s -u %s -p%s %s “;//默认备份文件名(备份表结构和数据)$file_format = $date_format.’_all.’.$this->db_config[‘back_file_suffix’];//默认备份全部的shell$this->back_shell = $common_shell.’ > %s’;switch ($this->db_config[‘back_type’]) {case ‘1’:break;case ‘2’://只备份表结构$file_format = $date_format.’_table_structure.’.$this->db_config[‘back_file_suffix’];$this->back_shell = $common_shell.’ –no-data > %s’;break;:$file_format = $date_format.’_table_data.’.$this->db_config[‘back_file_suffix’];$this->back_shell = $common_shell.’ –no-create-info > %s’;default:break;}$this->db_config[‘db_back_path’] = $this->db_config[‘db_back_path’].DIRECTORY_SEPARATOR.date(“Y-m-d”,time());//创建文件夹$this->make_dir($this->db_config[‘db_back_path’]);//构建文件全路径$this->file_name = $this->db_config[‘db_back_path’].DIRECTORY_SEPARATOR.$file_format;}, $mode = 0755, $recursive = true){if(!is_dir($path)){mkdir($path,$mode,$recursive);chmod($path,$mode);}return true;}{//字符串格式名生成shell命令$shell = sprintf($this->back_shell,$this->db_config[‘db_host’],$this->db_config[‘db_user’],$this->db_config[‘db_pwd’],$this->db_config[‘db_name’],$this->file_name);try{//执行shellshell_exec($shell);}catch (Exception $e){echo $e->getMessage();}}}$obj = new DB_back();$obj->start_back(); ?>

将这两个PHP文件放到同一目录中,我们假设放在/var/www/html/back/下

crontab -e* * * /usr/bin/php /var/www/html/back/DB_back.php

整个流程就是这样,如果需要修改相对应的配置,请直接修改DB_config.php配置文件

备注:在使用php的mkdir时,需要确定当前目录的父目录是否具有相应的写权限,如果没有,,请先进入终端进行chmod父目录,否则不会顺利创建目录

代码写的并不好,如有Bug或者建议,感谢指正

如此锐气,二十后生有之,六旬男子则更多见。

Linux下crontab+php实现Mysql数据库定时备份

相关文章:

你感兴趣的文章:

标签云: