Home  >  Article  >  Backend Development  >  PHP code to implement scheduled database backup and restore

PHP code to implement scheduled database backup and restore

小云云
小云云Original
2018-03-28 14:47:003565browse

本文主要和大家分享PHP代码实现数据库定时备份和还原,主要结合文字和代码的方式和大家分享,希望能帮助到大家。

ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执行. 
set_time_limit(0);// 通过set_time_limit(0)可以让程序无限制的执行下去 
$interval=60*30;// 每隔半小时运行 
do{ 
//这里是你要执行的代码 添加备份php或者还原的php的脚本, 
sleep($interval);// 等待5分钟 
}while(true); 

一、备份数据库并下载到本地【db_backup.php】 

Php代码  

<?php   
// 设置SQL文件保存文件名   
$filename=date("Y-m-d_H-i-s")."-".$cfg_dbname.".sql";   
// 所保存的文件名   
header("Content-disposition:filename=".$filename);   
header("Content-type:application/octetstream");   
header("Pragma:no-cache");   
header("Expires:0");   
// 获取当前页面文件路径,SQL文件就导出到此文件夹内   
$tmpFile = (dirname(__FILE__))."\\".$filename;   
// 用MySQLDump命令导出数据库   
exec("mysqldump -u$cfg_dbuser -p$cfg_dbpwd --default-character-set=utf8 $cfg_dbname > ".$tmpFile);   
$file = fopen($tmpFile, "r"); // 打开文件   
echo fread($file,filesize($tmpFile));   
fclose($file);   
exit;   
?>


二、还原数据库【db_restore.php】 

Php代码  

<form id="form1" name="form1" method="post" action="">   
【数据库SQL文件】:<input id="sqlFile" name="sqlFile" type="file" />   
<input id="submit" name="submit" type="submit" value="还原" />   
</form>   
<?php   
// 我的数据库信息都存放到config.php文件中,所以加载此文件,如果你的不是存放到该文件中,注释此行即可;   
require_once((dirname(__FILE__).&#39;/../../include/config.php&#39;));   
if ( isset ( $_POST[&#39;sqlFile&#39;] ) )   
{   
$file_name = $_POST[&#39;sqlFile&#39;]; //要导入的SQL文件名   
$dbhost = $cfg_dbhost; //数据库主机名   
$dbuser = $cfg_dbuser; //数据库用户名   
$dbpass = $cfg_dbpwd; //数据库密码   
$dbname = $cfg_dbname; //数据库名   
set_time_limit(0); //设置超时时间为0,表示一直执行。当php在safe mode模式下无效,此时可能会导致导入超时,此时需要分段导入   
$fp = @fopen($file_name, "r") or die("不能打开SQL文件 $file_name");//打开文件   
mysql_connect($dbhost, $dbuser, $dbpass) or die("不能连接数据库 $dbhost");//连接数据库   
mysql_select_db($dbname) or die ("不能打开数据库 $dbname");//打开数据库   
echo "<p>正在清空数据库,请稍等....<br>";   
$result = mysql_query("SHOW tables");   
while ($currow=mysql_fetch_array($result))   
{   
mysql_query("drop TABLE IF EXISTS $currow[0]");   
echo "清空数据表【".$currow[0]."】成功!<br>";   
}   
echo "<br>恭喜你清理MYSQL成功<br>";   
echo "正在执行导入数据库操作<br>";   
// 导入数据库的MySQL命令   
exec("mysql -u$cfg_dbuser -p$cfg_dbpwd $cfg_dbname < ".$file_name);   
echo "<br>导入完成!";   
mysql_close();   
}   
?>

  

网上摘抄2:

前段时间主机提供商服务器发生了问题,让人郁闷的事是将数据恢复到了一星期以前,导致好些博客数据丢失。
痛定思痛,想出了一个自动备份网站数据的方法。
1. 在服务器上实现数据转成SQL
为了实现服务器上的数据转成SQL脚本,需要在服务器上放一个PHP文件,这个PHP文件的目的是连接到数据库,然后将数据读取出来,最后再转成SQL。例如,我们放一个tosql.php文件在服务器htdocs目录,内容如下:

<?phperror_reporting(E_ALL & ~E_NOTICE);include_once &#39;application/configs/dbconfig.php&#39;;include_once &#39;application/includes/db.class.php&#39;;header(&#39;Expires: Mon, 26 Jul 1997 05:00:00 GMT&#39;);header(&#39;Last-Modified: &#39; . gmdate( &#39;D, d M Y H:i:s&#39;) . &#39; GMT&#39;);header(&#39;Cache-Control: no-store, no-cache, must-revalidate&#39;);header(&#39;Cache-Control: post-check=0, pre-check=0&#39;, false);header(&#39;Pragma: no-cache&#39;);header("Content-type: text/plain; charset=utf-8");$db = new db();$db->connect($config[&#39;db&#39;][&#39;host&#39;], $config[&#39;db&#39;][&#39;user&#39;], $config[&#39;db&#39;][&#39;pass&#39;]);$db->select_db($config[&#39;db&#39;][&#39;name&#39;]);$db->query(&#39;set names utf8&#39;);$sqldump = &#39;&#39;;//  我的表名都以tbs_开头$sql = "SHOW TABLE STATUS WHERE name like &#39;tbs_%&#39;";$query = $db->query($sql);while($table = $db->fetch_array($query)) {    $sqldump .= sql_dumptable($table[&#39;Name&#39;]);
}echo $sqldump;  
function sql_dumptable($table) 
{  global $db;  
  $tabledump = "DROP TABLE IF EXISTS $table;\n";  $createtable = $db->query("SHOW CREATE TABLE $table");  $create = $db->fetch_array($createtable);  $tabledump .= $create[1].";\n\n";  $rows = $db->query("SELECT * FROM $table");  $numfields = $db->num_fields($rows);  $numrows = $db->num_rows($rows);  while ($row = $db->fetch_array($rows)) 
  {    $comma = "";    $tabledump .= "INSERT INTO $table VALUES(";    for($i = 0; $i < $numfields; $i++){      $tabledump .= $comma."&#39;".mysql_escape_string($row[$i])."&#39;";      $comma = ",";
    }    $tabledump .= ");\n";
  }  $tabledump .= "\n";  return $tabledump;
}

2. 在本地新增一个PHP文件,目的是从服务器上获取SQL基本,然后写入到本地文件。这个PHP文件取名为nextdata.php,内容如下:

<?php$filename = dirname(__FILE__) . &#39;/data/tbs_&#39; . date(&#39;YmdHis&#39;, mktime() + 3600 * 8) . &#39;.sql&#39;;
$sqldump = file_get_contents(&#39;http://www.nextphp.com/tosql.php&#39;);file_put_contents($filename, $sqldump);

3. 实现定时备份
本地使用的是Windows操作系统,可以使用计划任务定时的执行备份任务,这样需要一个批处理文件。批处理文件名称为nextdata.bat,内如如下:

D:\wamp\bin\php\php5.3.5\php nextdata.php

经过上述三个步骤后,我们的计划任务就会定时的执行服务器上的tosql.php文件,然后将其内容写入到本地,从而实现了数据库的备份任务。

相关推荐:

数据库定时备份原理,代码

The above is the detailed content of PHP code to implement scheduled database backup and restore. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn