가상 호스트 가 없 는 깜찍 한 Mysql 데이터베이스 백업 스 크 립 트(PHP)추천
1.mydb.php//DB 클래스
<?
class db{
var $linkid;
var $sqlid;
var $record;
function db($host="",$username="",$password="",$database="")
{
if(!$this->linkid) @$this->linkid = mysql_connect($host, $username, $password) or die(" .");
@mysql_select_db($database,$this->linkid) or die(" ");
return $this->linkid;}
function query($sql)
{if($this->sqlid=mysql_query($sql,$this->linkid)) return $this->sqlid;
else {
$this->err_report($sql,mysql_error);
return false;}
}
function nr($sql_id="")
{if(!$sql_id) $sql_id=$this->sqlid;
return mysql_num_rows($sql_id);}
function nf($sql_id="")
{if(!$sql_id) $sql_id=$this->sqlid;
return mysql_num_fields($sql_id);}
function nextrecord($sql_id="")
{if(!$sql_id) $sql_id=$this->sqlid;
if($this->record=mysql_fetch_array($sql_id)) return $this->record;
else return false;
}
function f($name)
{
if($this->record[$name]) return $this->record[$name];
else return false;
}
function close() {mysql_close($this->linkid);}
function lock($tblname,$op="WRITE")
{if(mysql_query("lock tables ".$tblname." ".$op)) return true; else return false;}
function unlock()
{if(mysql_query("unlock tables")) return true; else return false;}
function ar() {
return @mysql_affected_rows($this->linkid);
}
function i_id() {
return mysql_insert_id();
}
function err_report($sql,$err)
{
echo "Mysql <br>";
echo " :".$sql."<br>";
echo " :".$err;
}
/**************************************** ***************************/
}?>
2.backup.php//백업 스 크 립 트
<?
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$mysqlhost="localhost"; //host name
$mysqluser="root"; //login name
$mysqlpwd=""; //password
$mysqldb=""; //name of database
include("mydb.php");
$d=new db($mysqlhost,$mysqluser,$mysqlpwd,$mysqldb);
/*-------------- --------------*/if(!$_POST['act']){/*----------------------*/
$msgs[]=" backup";
$msgs[]=" , ";
$msgs[]=" , ";
show_msg($msgs);
?>
<form name="form1" method="post" action="backup.php">
<table width="99%" border="1" cellpadding='0' cellspacing='1'>
<tr align="center" class='header'><td colspan="2"> </td></tr>
<tr><td colspan="2"> </td></tr>
<tr><td><input type="radio" name="bfzl" value="quanbubiao"> </td><td> </td></tr>
<tr><td><input type="radio" name="bfzl" value="danbiao">
<select name="tablename"><option value=""> </option>
<?
$d->query("show table status from $mysqldb");
while($d->nextrecord()){
echo "<option value='".$d->f('Name')."'>".$d->f('Name')."</option>";}
?>
</select></td><td> </td></tr>
<tr><td colspan="2"> </td></tr>
<tr><td colspan="2"><input type="checkbox" name="fenjuan" value="yes">
<input name="filesize" type="text" size="10">K</td></tr>
<tr><td colspan="2"> </td></tr>
<tr><td colspan="2"><input type="radio" name="weizhi" value="server" checked> </td></tr><tr class="cells"><td colspan='2'> <input type="radio" name="weizhi" value="localpc">
</td></tr>
<tr><td colspan="2" align='center'><input type="submit" name="act" value=" "></td></tr>
</table></form>
<?/*------------- -------------*/}/*---------------------------------*/
/*----*/else{/*-------------- -----------------------------------------*/
if($_POST['weizhi']=="localpc"&&$_POST['fenjuan']=='yes')
{$msgs[]=" , ";
show_msg($msgs); pageend();}
if($_POST['fenjuan']=="yes"&&!$_POST['filesize'])
{$msgs[]=" , ";
show_msg($msgs); pageend();}
if($_POST['weizhi']=="server"&&!writeable("./backup"))
{$msgs[]=" './backup' , ";
show_msg($msgs); pageend();}
/*---------- -------------*/if($_POST['bfzl']=="quanbubiao"){/*----*/
/*---- */if(!$_POST['fenjuan']){/*--------------------------------*/
if(!$tables=$d->query("show table status from $mysqldb"))
{$msgs[]=" "; show_msg($msgs); pageend();}
$sql="";
while($d->nextrecord($tables))
{
$table=$d->f("Name");
$sql.=make_header($table);
$d->query("select * from $table");
$num_fields=$d->nf();
while($d->nextrecord())
{$sql.=make_record($table,$num_fields);}
}
$filename=date("Ymd",time())."_all.sql";
if($_POST['weizhi']=="localpc") down_file($sql,$filename);
elseif($_POST['weizhi']=="server")
{if(write_file($sql,$filename))
$msgs[]=" , './backup/$filename'";
else $msgs[]=" ";
show_msg($msgs);
pageend();
}
/*----------------- */}/*-----------------------*/
/*----------------- */else{/*-------------------------*/
if(!$_POST['filesize'])
{$msgs[]=" "; show_msg($msgs);pageend();}
if(!$tables=$d->query("show table status from $mysqldb"))
{$msgs[]=" "; show_msg($msgs); pageend();}
$sql=""; $p=1;
$filename=date("Ymd",time())."_all";
while($d->nextrecord($tables))
{
$table=$d->f("Name");
$sql.=make_header($table);
$d->query("select * from $table");
$num_fields=$d->nf();
while($d->nextrecord())
{$sql.=make_record($table,$num_fields);
if(strlen($sql)>=$_POST['filesize']*1000){
$filename.=("_v".$p.".sql");
if(write_file($sql,$filename))
$msgs[]=" - -".$p."- , './backup/$filename'";
else $msgs[]=" -".$_POST['tablename']."- ";
$p++;
$filename=date("Ymd",time())."_all";
$sql="";}
}
}
if($sql!=""){$filename.=("_v".$p.".sql");
if(write_file($sql,$filename))
$msgs[]=" - -".$p."- , './backup/$filename'";}
show_msg($msgs);
/*--------------------- */}/*--------------------------------------*/
/*-------- */}/*---------------------------------------------*/
/*-------- ------*/elseif($_POST['bfzl']=="danbiao"){/*------------*/
if(!$_POST['tablename'])
{$msgs[]=" "; show_msg($msgs); pageend();}
/*-------- */if(!$_POST['fenjuan']){/*-------------------------------*/
$sql=make_header($_POST['tablename']);
$d->query("select * from ".$_POST['tablename']);
$num_fields=$d->nf();
while($d->nextrecord())
{$sql.=make_record($_POST['tablename'],$num_fields);}
$filename=date("Ymd",time())."_".$_POST['tablename'].".sql";
if($_POST['weizhi']=="localpc") down_file($sql,$filename);
elseif($_POST['weizhi']=="server")
{if(write_file($sql,$filename))
$msgs[]=" -".$_POST['tablename']."- , './backup/$filename'";
else $msgs[]=" -".$_POST['tablename']."- ";
show_msg($msgs);
pageend();
}
/*---------------- */}/*------------------------------------*/
/*---------------- */else{/*--------------------------------------*/
if(!$_POST['filesize'])
{$msgs[]=" "; show_msg($msgs);pageend();}
$sql=make_header($_POST['tablename']); $p=1;
$filename=date("Ymd",time())."_".$_POST['tablename'];
$d->query("select * from ".$_POST['tablename']);
$num_fields=$d->nf();
while ($d->nextrecord())
{
$sql.=make_record($_POST['tablename'],$num_fields);
if(strlen($sql)>=$_POST['filesize']*1000){
$filename.=("_v".$p.".sql");
if(write_file($sql,$filename))
$msgs[]=" -".$_POST['tablename']."- -".$p."- , './backup/$filename'";
else $msgs[]=" -".$_POST['tablename']."- ";
$p++;
$filename=date("Ymd",time())."_".$_POST['tablename'];
$sql="";}
}
if($sql!=""){$filename.=("_v".$p.".sql");
if(write_file($sql,$filename))
$msgs[]=" -".$_POST['tablename']."- -".$p."- , './backup/$filename'";}
show_msg($msgs);
/*---------- */}/*--------------------------------------------------*/
/*---------- */}/*----------------------------------------------*/
/*---*/}/*------------- ------------------------------------------*/
function write_file($sql,$filename)
{
$re=true;
if(!@$fp=fopen("./backup/".$filename,"w+")) {$re=false; echo "failed to open target file";}
if(!@fwrite($fp,$sql)) {$re=false; echo "failed to write file";}
if(!@fclose($fp)) {$re=false; echo "failed to close target file";}
return $re;
}
function down_file($sql,$filename)
{
ob_end_clean();
header("Content-Encoding: none");
header("Content-Type: ".(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? 'application/octetstream' : 'application/octet-stream'));
header("Content-Disposition: ".(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? 'inline; ' : 'attachment; ')."filename=".$filename);
header("Content-Length: ".strlen($sql));
header("Pragma: no-cache");
header("Expires: 0");
echo $sql;
$e=ob_get_contents();
ob_end_clean();
}
function writeable($dir)
{
if(!is_dir($dir)) {
@mkdir($dir, 0777);
}
if(is_dir($dir))
{
if($fp = @fopen("$dir/test.test", 'w'))
{
@fclose($fp);
@unlink("$dir/test.test");
$writeable = 1;
}
else {
$writeable = 0;
}
}
return $writeable;
}
function make_header($table)
{global $d;
$sql="DROP TABLE IF EXISTS ".$table."
";
$d->query("show create table ".$table);
$d->nextrecord();
$tmp=preg_replace("/
/","",$d->f("Create Table"));
$sql.=$tmp."
";
return $sql;
}
function make_record($table,$num_fields)
{global $d;
$comma="";
$sql .= "INSERT INTO ".$table." VALUES(";
for($i = 0; $i < $num_fields; $i++)
{$sql .= ($comma."'".mysql_escape_string($d->record[$i])."'"); $comma = ",";}
$sql .= ")
";
return $sql;
}
function show_msg($msgs)
{
$title=" :";
echo "<table width='100%' border='1' cellpadding='0' cellspacing='1'>";
echo "<tr><td>".$title."</td></tr>";
echo "<tr><td><br><ul>";
while (list($k,$v)=each($msgs))
{
echo "<li>".$v."</li>";
}
echo "</ul></td></tr></table>";
}
function pageend()
{
exit();
}
?>
3.restore.php//복원 스 크 립 트
<?
session_start();
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$mysqlhost="localhost"; //host name
$mysqluser="root"; //login name
$mysqlpwd=""; //password
$mysqldb=""; //name of database
include("mydb.php");
$d=new db($mysqlhost,$mysqluser,$mysqlpwd,$mysqldb);
/****** */if(!$_POST['act']&&!$_SESSION['data_file']){/**********************/
$msgs[]=" , , , ";
$msgs[]=" dShop , ";
$msgs[]=" , ";
$msgs[]=" , 1, ";
show_msg($msgs);
?>
<form action="" method="post" enctype="multipart/form-data" name="restore.php">
<table width="91%" border="0" cellpadding="0" cellspacing="1">
<tr align="center" class="header"><td colspan="2" align="center"> </td></tr>
<tr><td width="33%"><input type="radio" name="restorefrom" value="server" checked>
</td><td width="67%"><select name="serverfile">
<option value="">- -</option>
<?
$handle=opendir('./backup');
while ($file = readdir($handle)) {
if(eregi("^[0-9]{8,8}([0-9a-z_]+)(\.sql)$",$file)) echo "<option value='$file'>$file</option>";}
closedir($handle);
?>
</select> </td></tr>
<tr><td><input type="radio" name="restorefrom" value="localpc"> </td>
<td><input type="hidden" name="MAX_FILE_SIZE" value="1500000"><input type="file" name="myfile"></td></tr>
<tr><td colspan="2" align="center"> <input type="submit" name="act" value=" "></td> </tr></table></form>
<?/************************** */}/*************************************/
/**************************** */if($_POST['act']==" "){/**************/
/*************** */if($_POST['restorefrom']=="server"){/**************/
if(!$_POST['serverfile'])
{$msgs[]=" , ";
show_msg($msgs); pageend(); }
if(!eregi("_v[0-9]+",$_POST['serverfile']))
{$filename="./backup/".$_POST['serverfile'];
if(import($filename)) $msgs[]=" ".$_POST['serverfile']." ";
else $msgs[]=" ".$_POST['serverfile']." ";
show_msg($msgs); pageend();
}
else
{
$filename="./backup/".$_POST['serverfile'];
if(import($filename)) $msgs[]=" ".$_POST['serverfile']." ";
else {$msgs[]=" ".$_POST['serverfile']." ";show_msg($msgs);pageend();}
$voltmp=explode("_v",$_POST['serverfile']);
$volname=$voltmp[0];
$volnum=explode(".sq",$voltmp[1]);
$volnum=intval($volnum[0])+1;
$tmpfile=$volname."_v".$volnum.".sql";
if(file_exists("./backup/".$tmpfile))
{
$msgs[]=" 3 : ".$tmpfile.", , ";
$_SESSION['data_file']=$tmpfile;
show_msg($msgs);
sleep(3);
echo "<script language='javascript'>";
echo "location='restore.php';";
echo "</script>";
}
else
{
$msgs[]=" ";
show_msg($msgs);
}
}
/************** */}/********************************************/
/***************** */if($_POST['restorefrom']=="localpc"){/**************/
switch ($_FILES['myfile']['error'])
{
case 1:
case 2:
$msgs[]=" , ";
break;
case 3:
$msgs[]=" ";
break;
case 4:
$msgs[]=" ";
break;
case 0:
break;
}
if($msgs){show_msg($msgs);pageend();}
$fname=date("Ymd",time())."_".sjs(5).".sql";
if (is_uploaded_file($_FILES['myfile']['tmp_name'])) {
copy($_FILES['myfile']['tmp_name'], "./backup/".$fname);}
if (file_exists("./backup/".$fname))
{
$msgs[]=" ";
if(import("./backup/".$fname)) {$msgs[]=" "; unlink("./backup/".$fname);}
else $msgs[]=" ";
}
else ($msgs[]=" ");
show_msg($msgs);
/**** *****/}/****************************************************/
/**************************** */}/**********************************/
/************************* **********************************/
if(!$_POST['act']&&$_SESSION['data_file'])
{
$filename="./backup/".$_SESSION['data_file'];
if(import($filename)) $msgs[]=" ".$_SESSION['data_file']." ";
else {$msgs[]=" ".$_SESSION['data_file']." ";show_msg($msgs);pageend();}
$voltmp=explode("_v",$_SESSION['data_file']);
$volname=$voltmp[0];
$volnum=explode(".sq",$voltmp[1]);
$volnum=intval($volnum[0])+1;
$tmpfile=$volname."_v".$volnum.".sql";
if(file_exists("./backup/".$tmpfile))
{
$msgs[]=" 3 : ".$tmpfile.", , ";
$_SESSION['data_file']=$tmpfile;
show_msg($msgs);
sleep(3);
echo "<script language='javascript'>";
echo "location='restore.php';";
echo "</script>";
}
else
{
$msgs[]=" ";
unset($_SESSION['data_file']);
show_msg($msgs);
}
}
/********************** *******************************/
function import($fname)
{global $d;
$sqls=file($fname);
foreach($sqls as $sql)
{
str_replace("\r","",$sql);
str_replace("
","",$sql);
if(!$d->query(trim($sql))) return false;
}
return true;
}
function show_msg($msgs)
{
$title=" :";
echo "<table width='100%' border='1' cellpadding='0' cellspacing='1'>";
echo "<tr><td>".$title."</td></tr>";
echo "<tr><td><br><ul>";
while (list($k,$v)=each($msgs))
{
echo "<li>".$v."</li>";
}
echo "</ul></td></tr></table>";
}
function pageend()
{
exit();
}
?>
파일 구조 가 매우 뚜렷 해서 파일 2 와 3 에 데이터베이스 서버 의 주소,사용자 이름,비밀 번 호 를 설정 하면 복원 데 이 터 를 백업 할 수 있다.주의해 야 할 것 은:·같은 등급 의 디 렉 터 리 아래 에 Backup 디 렉 터 리 를 만 들 려 면 내 보 낼 스 크 립 트 를 저장 할 수 있 는 권한 이 필요 합 니 다.·백업 한 데이터베이스 가 비교적 클 때 서버 스 크 립 트 의 시간 초과 시간 을 좀 더 늘 려 야 합 니 다.·볼 륨 백업 을 지원 합 니 다.복원 할 때 볼 륨 백업 의 첫 번 째 스 크 립 트 를 선택 하면 모든 스 크 립 트 가 자동 으로 복 원 됩 니 다.·볼 륨 파일 크기 는 크게 하지 말고 2MB 를 넘 지 않 는 것 이 좋 습 니 다.·보안 상 스 크 립 트 는 서버 에서 삭제 하 는 것 을 잊 지 마 세 요.압축 파일 다운로드