php恢复数据库数据库,php代码:备份、恢复sql数据库

分类: LINUX

2006-02-13 17:55:29

php代码:备份、恢复sql数据库

require('includes/application_top.php');

if ($HTTP_GET_VARS['action']) {

switch ($HTTP_GET_VARS['action']) {

case 'forget':

tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key = 'DB_LAST_RESTORE'");

$messageStack->add_session(SUCCESS_LAST_RESTORE_CLEARED, 'success');

tep_redirect(tep_href_link(FILENAME_BACKUP));

break;

case 'backupnow':

tep_set_time_limit(0);

$schema = '# citespa, Open Source E-Commerce Solutions' . " " .

'# ' . " " .

'#' . " " .

'# Database Backup For ' . STORE_NAME . " " .

'# Copyright (c) ' . date('Y') . ' ' . STORE_OWNER . " " .

'#' . " " .

'# Database: ' . DB_DATABASE . " " .

'# Database Server: ' . DB_SERVER . " " .

'#' . " " .

'# Backup Date: ' . date(PHP_DATE_TIME_FORMAT) . " ";

$tables_query = tep_db_query('show tables');

while ($tables = tep_db_fetch_array($tables_query)) {

list(,$table) = each($tables);

$schema .= 'drop table if exists ' . $table . ';' . " " .

'create table ' . $table . ' (' . " ";

$table_list = array();

$fields_query = tep_db_query("show fields from " . $table);

while ($fields = tep_db_fetch_array($fields_query)) {

$table_list[] = $fields['Field'];

$schema .= '  ' . $fields['Field'] . ' ' . $fields['Type'];

if (strlen($fields['Default']) > 0) $schema .= ' default '' . $fields['Default'] . ''';

if ($fields['Null'] != 'YES') $schema .= ' not null';

if (isset($fields['Extra'])) $schema .= ' ' . $fields['Extra'];

$schema .= ',' . " ";

}

$schema = ereg_replace(", $", '', $schema);

// Add the keys

$index = array();

$keys_query = tep_db_query("show keys from " . $table);

while ($keys = tep_db_fetch_array($keys_query)) {

$kname = $keys['Key_name'];

if (!isset($index[$kname])) {

$index[$kname] = array('unique' => !$keys['Non_unique'],

'columns' => array());

}

$index[$kname]['columns'][] = $keys['Column_name'];

}

while (list($kname, $info) = each($index)) {

$schema .= ',' . " ";

$columns = implode($info['columns'], ', ');

if ($kname == 'PRIMARY') {

$schema .= '  PRIMARY KEY (' . $columns . ')';

} elseif ($info['unique']) {

$schema .= '  UNIQUE ' . $kname . ' (' . $columns . ')';

} else {

$schema .= '  KEY ' . $kname . ' (' . $columns . ')';

}

}

$schema .= " " . ');' . " ";

// Dump the data

$rows_query = tep_db_query("select " . implode(',', $table_list) . " from " . $table);

while ($rows = tep_db_fetch_array($rows_query)) {

$schema_insert = 'insert into ' . $table . ' (' . implode(', ', $table_list) . ') values (';

reset($table_list);

while (list(,$i) = each($table_list)) {

if (!isset($rows[$i])) {

$schema_insert .= 'NULL, ';

} elseif ($rows[$i] != '') {

$row = addslashes($rows[$i]);

$row = ereg_replace(" #", " ".'#', $row);

$schema_insert .= ''' . $row . '', ';

} else {

$schema_insert .= ''', ';

}

}

$schema_insert = ereg_replace(', $', '', $schema_insert) . ');' . " ";

$schema .= $schema_insert;

}

$schema .= " ";

}

if ($HTTP_POST_VARS['download'] == 'yes') {

$backup_file = 'db_' . DB_DATABASE . '-' . date('YmdHis') . '.sql';

switch ($HTTP_POST_VARS['compress']) {

case 'no':

header('Content-type: application/x-octet-stream');

header('Content-disposition: attachment; filename=' . $backup_file);

echo $schema;

exit;

break;

case 'gzip':

if ($fp = fopen(DIR_FS_BACKUP . $backup_file, 'w')) {

fputs($fp, $schema);

fclose($fp);

exec(LOCAL_EXE_GZIP . ' ' . DIR_FS_BACKUP . $backup_file);

$backup_file .= '.gz';

}

if ($fp = fopen(DIR_FS_BACKUP . $backup_file, 'rb')) {

$buffer = fread($fp, filesize(DIR_FS_BACKUP . $backup_file));

fclose($fp);

unlink(DIR_FS_BACKUP . $backup_file);

header('Content-type: application/x-octet-stream');

header('Content-disposition: attachment; filename=' . $backup_file);

echo $buffer;

exit;

}

break;

case 'zip':

if ($fp = fopen(DIR_FS_BACKUP . $backup_file, 'w')) {

fputs($fp, $schema);

fclose($fp);

exec(LOCAL_EXE_ZIP . ' -j ' . DIR_FS_BACKUP . $backup_file . '.zip ' . DIR_FS_BACKUP . $backup_file);

unlink(DIR_FS_BACKUP . $backup_file);

$backup_file .= '.zip';

}

if ($fp = fopen(DIR_FS_BACKUP . $backup_file, 'rb')) {

$buffer = fread($fp, filesize(DIR_FS_BACKUP . $backup_file));

fclose($fp);

unlink(DIR_FS_BACKUP . $backup_file);

header('Content-type: application/x-octet-stream');

header('Content-disposition: attachment; filename=' . $backup_file);

echo $buffer;

exit;

}

}

} else {

$backup_file = DIR_FS_BACKUP . 'db_' . DB_DATABASE . '-' . date('YmdHis') . '.sql';

if ($fp = fopen($backup_file, 'w')) {

fputs($fp, $schema);

fclose($fp);

switch ($HTTP_POST_VARS['compress']) {

case 'gzip':

exec(LOCAL_EXE_GZIP . ' ' . $backup_file);

break;

case 'zip':

exec(LOCAL_EXE_ZIP . ' -j ' . $backup_file . '.zip ' . $backup_file);

unlink($backup_file);

}

}

$messageStack->add_session(SUCCESS_DATABASE_SAVED, 'success');

tep_redirect(tep_href_link(FILENAME_BACKUP));

}

break;

case 'restorenow':

case 'restorelocalnow':

tep_set_time_limit(0);

if ($HTTP_GET_VARS['action'] == 'restorenow') {

$read_from = $HTTP_GET_VARS['file'];

if (file_exists(DIR_FS_BACKUP . $HTTP_GET_VARS['file'])) {

$restore_file = DIR_FS_BACKUP . $HTTP_GET_VARS['file'];

$extension = substr($HTTP_GET_VARS['file'], -3);

if ( ($extension == 'sql') || ($extension == '.gz') || ($extension == 'zip') ) {

switch ($extension) {

case 'sql':

$restore_from = $restore_file;

$remove_raw = false;

break;

case '.gz':

$restore_from = substr($restore_file, 0, -3);

exec(LOCAL_EXE_GUNZIP . ' ' . $restore_file . ' -c > ' . $restore_from);

$remove_raw = true;

break;

case 'zip':

$restore_from = substr($restore_file, 0, -4);

exec(LOCAL_EXE_UNZIP . ' ' . $restore_file . ' -d ' . DIR_FS_BACKUP);

$remove_raw = true;

}

if ( ($restore_from) && (file_exists($restore_from)) && (filesize($restore_from) > 15000) ) {

$fd = fopen($restore_from, 'rb');

$restore_query = fread($fd, filesize($restore_from));

fclose($fd);

}

}

}

} elseif ($HTTP_GET_VARS['action'] == 'restorelocalnow') {

if ($HTTP_POST_FILES['sql_file']) {

$uploaded_file = $HTTP_POST_FILES['sql_file']['tmp_name'];

$read_from = basename($HTTP_POST_FILES['sql_file']['name']);

} elseif ($HTTP_POST_VARS['sql_file']) {

$uploaded_file = $HTTP_POST_VARS['sql_file'];

$read_from = basename($HTTP_POST_VARS['sql_file_name']);

} else {

$uploaded_file = $sql_file;

$read_from = basename($sql_file_name);

}

if ($uploaded_file != 'none') {

if (tep_is_uploaded_file($uploaded_file)) {

$restore_query = fread(fopen($uploaded_file, 'r'), filesize($uploaded_file));

}

}

}

if ($restore_query) {

$sql_array = array();

$sql_length = strlen($restore_query);

$pos = strpos($restore_query, ';');

for ($i=$pos; $i            if ($restore_query[0] == '#') {

$restore_query = ltrim(substr($restore_query, strpos($restore_query, " ")));

$sql_length = strlen($restore_query);

$i = strpos($restore_query, ';')-1;

continue;

}

if ($restore_query[($i+1)] == " ") {

for ($j=($i+2); $j                if (trim($restore_query[$j]) != '') {

$next = substr($restore_query, $j, 6);

if ($next[0] == '#') {

// find out where the break position is so we can remove this line (#comment line)

for ($k=$j; $k                      if ($restore_query[$k] == " ") break;

}

$query = substr($restore_query, 0, $i+1);

$restore_query = substr($restore_query, $k);

// join the query before the comment appeared, with the rest of the dump

$restore_query = $query . $restore_query;

$sql_length = strlen($restore_query);

$i = strpos($restore_query, ';')-1;

continue 2;

}

break;

}

}

if ($next == '') { // get the last insert query

$next = 'insert';

}

if ( (eregi('create', $next)) || (eregi('insert', $next)) || (eregi('drop t', $next)) ) {

$next = '';

$sql_array[] = substr($restore_query, 0, $i);

$restore_query = ltrim(substr($restore_query, $i+1));

$sql_length = strlen($restore_query);

$i = strpos($restore_query, ';')-1;

}

}

}

$tables_query = tep_db_query('show tables');

while ($tables = tep_db_fetch_array($tables_query)) {

list(,$table) = each($tables);

tep_db_query("drop table " . $table);

}

for ($i=0; $itep_db_query($sql_array[$i]);

}

tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key = 'DB_LAST_RESTORE'");

tep_db_query("insert into " . TABLE_CONFIGURATION . " values ('', 'Last Database Restore', 'DB_LAST_RESTORE', '" . $read_from . "', 'Last database restore file', '6', '', '', now(), '', '')");

if ($remove_raw) {

unlink($restore_from);

}

}

$messageStack->add_session(SUCCESS_DATABASE_RESTORED, 'success');

tep_redirect(tep_href_link(FILENAME_BACKUP));

break;

case 'download':

$extension = substr($HTTP_GET_VARS['file'], -3);

if ( ($extension == 'zip') || ($extension == '.gz') || ($extension == 'sql') ) {

if ($fp = fopen(DIR_FS_BACKUP . $HTTP_GET_VARS['file'], 'rb')) {

$buffer = fread($fp, filesize(DIR_FS_BACKUP . $HTTP_GET_VARS['file']));

fclose($fp);

header('Content-type: application/x-octet-stream');

header('Content-disposition: attachment; filename=' . $HTTP_GET_VARS['file']);

echo $buffer;

exit;

}

} else {

$messageStack->add(ERROR_DOWNLOAD_LINK_NOT_ACCEPTABLE, 'error');

}

break;

case 'deleteconfirm':

if (strstr($HTTP_GET_VARS['file'], '..')) tep_redirect(tep_href_link(FILENAME_BACKUP));

tep_remove(DIR_FS_BACKUP . '/' . $HTTP_GET_VARS['file']);

if (!$tep_remove_error) {

$messageStack->add_session(SUCCESS_BACKUP_DELETED, 'success');

tep_redirect(tep_href_link(FILENAME_BACKUP));

}

break;

}

}

// check if the backup directory exists

$dir_ok = false;

if (is_dir(DIR_FS_BACKUP)) {

$dir_ok = true;

if (!is_writeable(DIR_FS_BACKUP)) $messageStack->add(ERROR_BACKUP_DIRECTORY_NOT_WRITEABLE, 'error');

} else {

$messageStack->add(ERROR_BACKUP_DIRECTORY_DOES_NOT_EXIST, 'error');

}

?>

>

$entry = $contents[$files];

$check = 0;

if (((!$HTTP_GET_VARS['file']) || ($HTTP_GET_VARS['file'] == $entry)) && (!$buInfo) && ($HTTP_GET_VARS['action'] != 'backup') && ($HTTP_GET_VARS['action'] != 'restorelocal')) {

$file_array['file'] = $entry;

$file_array['date'] = date(PHP_DATE_TIME_FORMAT, filemtime(DIR_FS_BACKUP . $entry));

$file_array['size'] = number_format(filesize(DIR_FS_BACKUP . $entry)) . ' bytes';

switch (substr($entry, -3)) {

case 'zip': $file_array['compression'] = 'ZIP'; break;

case '.gz': $file_array['compression'] = 'GZIP'; break;

default: $file_array['compression'] = TEXT_NO_EXTENSION; break;

}

$buInfo = new objectInfo($file_array);

}

if (is_object($buInfo) && ($entry == $buInfo->file)) {

echo '

' . " ";

$onclick_link = 'file=' . $buInfo->file . '&action=restore';

} else {

echo '

' . " ";

$onclick_link = 'file=' . $entry;

}

?>

' . tep_image(DIR_WS_ICONS . 'file_download.gif', ICON_FILE_DOWNLOAD) . ' ' . $entry; ?>

bytes

file) ) { echo tep_image(DIR_WS_IMAGES . 'icon_arrow_right.gif', ''); } else { echo '' . tep_image(DIR_WS_IMAGES . 'icon_info.gif', IMAGE_ICON_INFO) . ''; } ?>

' . tep_image_button('button_backup.gif', IMAGE_BACKUP) . ''; if ( ($HTTP_GET_VARS['action'] != 'restorelocal') && ($dir) ) echo '  ' . tep_image_button('button_restore.gif', IMAGE_RESTORE) . ''; ?>

' . TEXT_FORGET . ''; ?>

' . TEXT_INFO_HEADING_NEW_BACKUP . '');

$contents = array('form' => tep_draw_form('backup', FILENAME_BACKUP, 'action=backupnow'));

$contents[] = array('text' => TEXT_INFO_NEW_BACKUP);

if ($messageStack->size > 0) {

$contents[] = array('text' => '

' . tep_draw_radio_field('compress', 'no', true) . ' ' . TEXT_INFO_USE_NO_COMPRESSION);

$contents[] = array('text' => '

' . tep_draw_radio_field('download', 'yes', true) . ' ' . TEXT_INFO_DOWNLOAD_ONLY . '*

*' . TEXT_INFO_BEST_THROUGH_HTTPS);

} else {

$contents[] = array('text' => '

' . tep_draw_radio_field('compress', 'gzip', true) . ' ' . TEXT_INFO_USE_GZIP);

$contents[] = array('text' => tep_draw_radio_field('compress', 'zip') . ' ' . TEXT_INFO_USE_ZIP);

$contents[] = array('text' => tep_draw_radio_field('compress', 'no') . ' ' . TEXT_INFO_USE_NO_COMPRESSION);

$contents[] = array('text' => '

' . tep_draw_checkbox_field('download', 'yes') . ' ' . TEXT_INFO_DOWNLOAD_ONLY . '*

*' . TEXT_INFO_BEST_THROUGH_HTTPS);

}

$contents[] = array('align' => 'center', 'text' => '

' . tep_image_submit('button_backup.gif', IMAGE_BACKUP) . ' ' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '');

break;

case 'restore':

$heading[] = array('text' => '' . $buInfo->date . '');

$contents[] = array('text' => tep_break_string(sprintf(TEXT_INFO_RESTORE, DIR_FS_BACKUP . (($buInfo->compression != TEXT_NO_EXTENSION) ? substr($buInfo->file, 0, strrpos($buInfo->file, '.')) : $buInfo->file), ($buInfo->compression != TEXT_NO_EXTENSION) ? TEXT_INFO_UNPACK : ''), 35, ' '));

$contents[] = array('align' => 'center', 'text' => '

' . tep_image_button('button_restore.gif', IMAGE_RESTORE) . ' ' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '');

break;

case 'restorelocal':

$heading[] = array('text' => '' . TEXT_INFO_HEADING_RESTORE_LOCAL . '');

$contents = array('form' => tep_draw_form('restore', FILENAME_BACKUP, 'action=restorelocalnow', 'post', 'enctype="multipart/form-data"'));

$contents[] = array('text' => TEXT_INFO_RESTORE_LOCAL . '

' . TEXT_INFO_BEST_THROUGH_HTTPS);

$contents[] = array('text' => '

' . tep_draw_file_field('sql_file'));

$contents[] = array('text' => TEXT_INFO_RESTORE_LOCAL_RAW_FILE);

$contents[] = array('align' => 'center', 'text' => '

' . tep_image_submit('button_restore.gif', IMAGE_restore) . ' ' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '');

break;

case 'delete':

$heading[] = array('text' => '' . $buInfo->date . '');

$contents = array('form' => tep_draw_form('delete', FILENAME_BACKUP, 'file=' . $buInfo->file . '&action=deleteconfirm'));

$contents[] = array('text' => TEXT_DELETE_INTRO);

$contents[] = array('text' => '

' . $buInfo->file . '');

$contents[] = array('align' => 'center', 'text' => '

' . tep_image_submit('button_delete.gif', IMAGE_DELETE) . ' ' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '');

break;

default:

if (is_object($buInfo)) {

$heading[] = array('text' => '' . $buInfo->date . '');

$contents[] = array('align' => 'center', 'text' => '' . tep_image_button('button_restore.gif', IMAGE_RESTORE) . ' ' . tep_image_button('button_delete.gif', IMAGE_DELETE) . '');

$contents[] = array('text' => '

' . TEXT_INFO_DATE . ' ' . $buInfo->date);

$contents[] = array('text' => TEXT_INFO_SIZE . ' ' . $buInfo->size);

$contents[] = array('text' => '

' . TEXT_INFO_COMPRESSION . ' ' . $buInfo->compression);

}

break;

}

if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {

echo '            ' . " ";

$box = new box;

echo $box->infoBox($heading, $contents);

echo '' . " ";

}

?>

阅读(2042) | 评论(0) | 转发(0) |

给主人留下些什么吧!~~

评论热议

请登录后评论。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHP可以通过使用命令行工具或者PHP扩展来实现数据库代码备份。 1. 使用命令行工具 (1)数据库备份 使用 mysqldump 工具可以将 MySQL 数据库导出为SQL脚本文件,从而实现备份。 示例代码: ``` system('mysqldump -u root -p dbname > backup.sql'); ``` 其中,-u指定数据库用户名,-p指定密码,dbname是要备份数据库名称,> 操作符将备份结果输出到 backup.sql 文件中。 (2)代码备份 使用 tar 命令可以将代码文件打包成一个压缩包,从而实现备份。 示例代码: ``` system('tar -zcvf backup.tar.gz /path/to/code'); ``` 其中,-z指定压缩格式为gzip,-c指定创建压缩包,-v指定显示详细信息,-f指定输出文件名,/path/to/code是要备份代码目录。 2. 使用PHP扩展 使用PHP的扩展包,我们可以更方便地备份数据和代码。以备份MySQL数据为例,可以使用PDO扩展连接数据库,然后使用PDOStatement::fetchAll()方法获取查询结果,最后将结果写入文件中。 示例代码: ``` $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'root', 'password'); $stmt = $pdo->query("SELECT * FROM mytable"); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); $fp = fopen('backup.sql', 'w'); foreach ($result as $row) { fwrite($fp, "INSERT INTO mytable (col1, col2) VALUES ('{$row['col1']}', '{$row['col2']}');"); } fclose($fp); ``` 其中,PDO::FETCH_ASSOC指定查询结果的格式为关联数组,将结果按照SQL语句的格式写入backup.sql文件中。 代码备份也可以使用PHP的ZipArchive扩展来实现。 示例代码: ``` $zip = new ZipArchive(); $zip->open('backup.zip', ZipArchive::CREATE); $files = array('/path/to/file1', '/path/to/file2'); foreach ($files as $file) { $zip->addFile($file); } $zip->close(); ``` 其中,ZipArchive::CREATE指定创建新的压缩包,$files是要备份文件列表,使用ZipArchive::addFile()方法将文件加入压缩包中,最后使用ZipArchive::close()方法关闭压缩包。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值