备份mysql数据的php代码

开发技术 作者: 2024-07-27 22:25:01
备份mysql数据的php代码

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

<?PHP

##################### 
//CONFIGURATIONS  
#####################
// Define the name of the backup directory
define('BACKUP_DIR','./myBackups' ) ; 
// Define  Database Credentials
define('HOST','localhost' ) ; 
define('USER','testd!b' ) ; 
define('PASSWORD','k^[email protected]#VV' ) ; 
define('DB_NAME','test123' ) ; 
/*
Define the filename for the sql file
If you plan to upload the  file to Amazon's S3 service,use only lower-case letters 
*/
$fileName = 'MysqLbackup--' . date('d-m-Y') . '@'.date('h.i.s').'.sql' ; 
// Set execution time limit
if(function_exists('max_execution_time')) {
if( ini_get('max_execution_time') > 0 )     set_time_limit(0) ;
}

###########################  

//END  OF  CONFIGURATIONS  

###########################

// Check if directory is already created and has the proper permissions
if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR,0700) ;
if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR,0700) ; 

// Create an ".htaccess" file,it will restrict direct accss to the backup-directory . 
$content = 'deny from all' ; 
$file = new SplFileObject(BACKUP_DIR . '/.htaccess',"w") ;
$file->fwrite($content) ;

$MysqLi = new MysqLi(HOST,USER,PASSWORD,DB_NAME) ;
if (MysqLi_connect_errno())
{
   printf("Connect Failed: %s",MysqLi_connect_error());
   exit();
}
 // Introduction information
 $return .= "--\n";
$return .= "-- A MysqL Backup System \n";
$return .= "--\n";
$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n";
$return = "--\n";
$return .= "-- Database : " . DB_NAME . "\n";
$return .= "--\n";
$return .= "-- --------------------------------------------------\n";
$return .= "-- ---------------------------------------------------\n";
$return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ;
$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ;
$tables = array() ; 
// Exploring what tables this database has
$result = $MysqLi->query('SHOW TABLES' ) ; 
// Cycle through "$result" and put content into an array
while ($row = $result->fetch_row()) 
{
$tables[] = $row[0] ;
}
// Cycle through each  table
 foreach($tables as $table)
 { 
// Get content of each table
$result = $MysqLi->query('SELECT * FROM '. $table) ; 
// Get number of fields (columns) of each table
$num_fields = $MysqLi->field_count  ;
// Add table information
$return .= "--\n" ;
$return .= '-- Tabel structure for table `' . $table . '`' . "\n" ;
$return .= "--\n" ;
$return.= 'DROP TABLE  IF EXISTS `'.$table.'`;' . "\n" ; 
// Get the table-shema
$shema = $MysqLi->query('SHOW CREATE TABLE '.$table) ;
// Extract table shema 
$tableshema = $shema->fetch_row() ; 
// Append table-shema into code
$return.= $tableshema[1].";" . "\n\n" ; 
// Cycle through each table-row
while($rowdata = $result->fetch_row()) 
{ 
// Prepare code that will insert data into table 
$return .= 'INSERT INTO `'.$table .'`  VALUES ( '  ;
// Extract data of each row 
for($i=0; $i<$num_fields; $i++)
{
$return .= '"'.$rowdata[$i] . "\"," ;
 }
 // Let's remove the last comma 
 $return = substr("$return",-1) ; 
 $return .= ");" ."\n" ;
 } 
 $return .= "\n\n" ; 
}
// Close the connection
$MysqLi->close() ;
$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; '  . "\n" ; 
$return .= 'COMMIT ; '  . "\n" ;
$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n"  ; 
//$file = file_put_contents($fileName,$return) ; 
$zip = new ZipArchive() ;
$resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip",ZIPARCHIVE::CREATE) ;
if( $resOpen ){
$zip->addFromString( $fileName,"$return" ) ;
    }
$zip->close() ;
$fileSize = get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ; 
$message = <<<msg
  <h2>BACKUP  completed,</h2><br> 
  the archive has the name of  : <b>  $fileName  </b> and it's file-size is :   $fileSize  .<br>
 This zip archive can't be accessed via a web browser,as it's stored into a protected directory . <br>
  It's highly recomended to transfer this backup to another filesystem,use your favorite FTP client to download the archieve . 
msg;
echo $message ; 

// Function to append proper Unit after file-size . 
function get_file_size_unit($file_size){
switch (true) {
    case ($file_size/1024 < 1) :
        return intval($file_size ) ." Bytes" ;
        break;
    case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1)  :
        return intval($file_size/1024) ." KB" ;
        break;
    default:
    return intval($file_size/(1024*1024)) ." MB" ;
}
}

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_51926.html