tp5-databackup
```
<?php
// +----------------------------------------------------------------------
// | Author: tp5er <tp5er@qq.com>
// | QQ Group: 368683534
// +----------------------------------------------------------------------
namespace tp5er;
use think\Db;
use think\Config;
class Backup
{
/**
* 文件指針
* @var resource
*/
private $fp;
/**
* 備份文件信息 part - 卷號,name - 文件名
* @var array
*/
private $file;
/**
* 當前打開文件大小
* @var integer
*/
private $size = 0;
/**
* 數據庫配置
* @var integer
*/
private $dbconfig = array();
/**
* 備份配置
* @var integer
*/
private $config = array(
'path' => './public/Data/',
//數據庫備份路徑
'part' => 20971520,
//數據庫備份卷大小
'compress' => 0,
//數據庫備份文件是否啟用壓縮 0不壓縮 1 壓縮
'level' => 9,
);
/**
* 數據庫備份構造方法
* @param array $file 備份或還原的文件信息
* @param array $config 備份配置信息
*/
public function __construct($config = [])
{
$this->config = array_merge($this->config, $config);
//初始化文件名
$this->setFile();
//初始化數據庫連接參數
$this->setDbConn();
//檢查文件是否可寫
if (!$this->checkPath($this->config['path'])) {
throw new \Exception("The current directory is not writable");
}
}
/**
* 設置腳本運行超時時間
* 0表示不限制,支持連貫操作
*/
public function setTimeout($time=null)
{
if (!is_null($time)) {
set_time_limit($time)||ini_set("max_execution_time", $time);
}
return $this;
}
/**
* 設置數據庫連接必備參數
* @param array $dbconfig 數據庫連接配置信息
* @return object
*/
public function setDbConn($dbconfig = [])
{
if (empty($dbconfig)) {
$this->dbconfig = config('database');
//$this->dbconfig = Config::get('database');
} else {
$this->dbconfig = $dbconfig;
}
return $this;
}
/**
* 設置備份文件名
* @param Array $file 文件名字
* @return object
*/
public function setFile($file = null)
{
if (is_null($file)) {
$this->file = ['name' => date('Ymd-His'), 'part' => 1];
} else {
if (!array_key_exists("name", $file) && !array_key_exists("part", $file)) {
$this->file = $file['1'];
} else {
$this->file = $file;
}
}
return $this;
}
//數據類連接
public static function connect()
{
return Db::connect();
}
//數據庫表列表
public function dataList($table = null,$type=1)
{
$db = self::connect();
if (is_null($table)) {
$list = $db->query("SHOW TABLE STATUS");
} else {
if ($type) {
$list = $db->query("SHOW FULL COLUMNS FROM {$table}");
}else{
$list = $db->query("show columns from {$table}");
}
}
return array_map('array_change_key_case', $list);
//$list;
}
//數據庫備份文件列表
public function fileList()
{
if (!is_dir($this->config['path'])) {
mkdir($this->config['path'], 0755, true);
}
$path = realpath($this->config['path']);
$flag = \FilesystemIterator::KEY_AS_FILENAME;
$glob = new \FilesystemIterator($path, $flag);
$list = array();
foreach ($glob as $name => $file) {
if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) {
$name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
$date = "{$name[0]}-{$name[1]}-{$name[2]}";
$time = "{$name[3]}:{$name[4]}:{$name[5]}";
$part = $name[6];
if (isset($list["{$date} {$time}"])) {
$info = $list["{$date} {$time}"];
$info['part'] = max($info['part'], $part);
$info['size'] = $info['size'] + $file->getSize();
} else {
$info['part'] = $part;
$info['size'] = $file->getSize();
}
$extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
$info['compress'] = $extension === 'SQL' ? '-' : $extension;
$info['time'] = strtotime("{$date} {$time}");
$list["{$date} {$time}"] = $info;
}
}
return $list;
}
public function getFile($type = '', $time = 0)
{
//
if (!is_numeric($time)) {
throw new \Exception("{$time} Illegal data type");
}
switch ($type) {
case 'time':
$name = date('Ymd-His', $time) . '-*.sql*';
$path = realpath($this->config['path']) . DIRECTORY_SEPARATOR . $name;
return glob($path);
break;
case 'timeverif':
$name = date('Ymd-His', $time) . '-*.sql*';
$path = realpath($this->config['path']) . DIRECTORY_SEPARATOR . $name;
$files = glob($path);
$list = array();
foreach ($files as $name) {
$basename = basename($name);
$match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
$gz = preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql.gz$/', $basename);
$list[$match[6]] = array($match[6], $name, $gz);
}
$last = end($list);
if (count($list) === $last[0]) {
return $list;
} else {
throw new \Exception("File {$files['0']} may be damaged, please check again");
}
break;
case 'pathname':
return "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql";
break;
case 'filename':
return "{$this->file['name']}-{$this->file['part']}.sql";
break;
case 'filepath':
return $this->config['path'];
break;
default:
$arr = array('pathname' => "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql", 'filename' => "{$this->file['name']}-{$this->file['part']}.sql", 'filepath' => $this->config['path'], 'file' => $this->file);
return $arr;
}
}
//刪除備份文件
public function delFile($time)
{
if ($time) {
$file = $this->getFile('time', $time);
array_map("unlink", $this->getFile('time', $time));
if (count($this->getFile('time', $time))) {
throw new \Exception("File {$path} deleted failed");
} else {
return $time;
}
} else {
throw new \Exception("{$time} Time parameter is incorrect");
}
}
/**
* 下載備份
* @Author: 浪哥 <939881475@qq.com>
* @param string $time
* @param integer $part
* @return array|mixed|string
*/
public function downloadFile($time, $part = 0)
{
$file = $this->getFile('time', $time);
$fileName = $file[$part];
if (file_exists($fileName)) {
ob_end_clean();
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($fileName));
header('Content-Disposition: attachment; filename=' . basename($fileName));
readfile($fileName);
} else {
throw new \Exception("{$time} File is abnormal");
}
}
public function import($start,$time)
{
//還原數據
$db = self::connect();
$this->file=$this->getFile('time',$time);
if ($this->config['compress']) {
$gz = gzopen($this->file[0], 'r');
$size = 0;
} else {
$size = filesize($this->file[0]);
$gz = fopen($this->file[0], 'r');
}
$sql = '';
if ($start) {
$this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start);
}
for ($i = 0; $i < 1000; $i++) {
$sql .= $this->config['compress'] ? gzgets($gz) : fgets($gz);
if (preg_match('/.*;$/', trim($sql))) {
if (false !== $db->execute($sql)) {
$start += strlen($sql);
} else {
return false;
}
$sql = '';
} elseif ($this->config['compress'] ? gzeof($gz) : feof($gz)) {
return 0;
}
}
return array($start, $size);
}
/**
* 寫入初始數據
* @return boolean true - 寫入成功,false - 寫入失敗
*/
public function Backup_Init()
{
$sql = "-- -----------------------------\n";
$sql .= "-- Think MySQL Data Transfer \n";
$sql .= "-- \n";
$sql .= "-- Host : " . $this->dbconfig['hostname'] . "\n";
$sql .= "-- Port : " . $this->dbconfig['hostport'] . "\n";
$sql .= "-- Database : " . $this->dbconfig['database'] . "\n";
$sql .= "-- \n";
$sql .= "-- Part : #{$this->file['part']}\n";
$sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
$sql .= "-- -----------------------------\n\n";
$sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
return $this->write($sql);
}
/**
* 備份表結構
* @param string $table 表名
* @param integer $start 起始行數
* @return boolean false - 備份失敗
*/
public function backup($table, $start)
{
$db = self::connect();
// 備份表結構
if (0 == $start) {
$result = $db->query("SHOW CREATE TABLE `{$table}`");
$sql = "\n";
$sql .= "-- -----------------------------\n";
$sql .= "-- Table structure for `{$table}`\n";
$sql .= "-- -----------------------------\n";
$sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
$sql .= trim($result[0]['Create Table']) . ";\n\n";
if (false === $this->write($sql)) {
return false;
}
}
//數據總數
$result = $db->query("SELECT COUNT(*) AS count FROM `{$table}`");
$count = $result['0']['count'];
//備份表數據
if ($count) {
//寫入數據注釋
if (0 == $start) {
$sql = "-- -----------------------------\n";
$sql .= "-- Records of `{$table}`\n";
$sql .= "-- -----------------------------\n";
$this->write($sql);
}
//備份數據記錄
$result = $db->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000");
foreach ($result as $row) {
$row = array_map('addslashes', $row);
$sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r", "\n"), array('\\r', '\\n'), implode("', '", $row)) . "');\n";
if (false === $this->write($sql)) {
return false;
}
}
//還有更多數據
if ($count > $start + 1000) {
//return array($start + 1000, $count);
return $this->backup($table, $start + 1000);
}
}
//備份下一表
return 0;
}
/**
* 優化表
* @param String $tables 表名
* @return String $tables
*/
public function optimize($tables = null)
{
if ($tables) {
$db = self::connect();
if (is_array($tables)) {
$tables = implode('`,`', $tables);
$list = $db->query("OPTIMIZE TABLE `{$tables}`");
} else {
$list = $db->query("OPTIMIZE TABLE `{$tables}`");
}
if ($list) {
return $list;
} else {
throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
}
} else {
throw new \Exception("Please specify the table to be repaired!");
}
}
/**
* 修復表
* @param String $tables 表名
* @return String $tables
*/
public function repair($tables = null)
{
if ($tables) {
$db = self::connect();
if (is_array($tables)) {
$tables = implode('`,`', $tables);
$list = $db->query("REPAIR TABLE `{$tables}`");
} else {
$list = $db->query("REPAIR TABLE `{$tables}`");
}
if ($list) {
return $list;
} else {
throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
}
} else {
throw new \Exception("Please specify the table to be repaired!");
}
}
/**
* 寫入SQL語句
* @param string $sql 要寫入的SQL語句
* @return boolean true - 寫入成功,false - 寫入失敗!
*/
private function write($sql)
{
$size = strlen($sql);
//由于壓縮原因,無法計算出壓縮后的長度,這里假設壓縮率為50%,
//一般情況壓縮率都會高于50%;
$size = $this->config['compress'] ? $size / 2 : $size;
$this->open($size);
return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
}
/**
* 打開一個卷,用于寫入數據
* @param integer $size 寫入數據的大小
*/
private function open($size)
{
if ($this->fp) {
$this->size += $size;
if ($this->size > $this->config['part']) {
$this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
$this->fp = null;
$this->file['part']++;
session('backup_file', $this->file);
$this->Backup_Init();
}
} else {
$backuppath = $this->config['path'];
$filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
if ($this->config['compress']) {
$filename = "{$filename}.gz";
$this->fp = @gzopen($filename, "a{$this->config['level']}");
} else {
$this->fp = @fopen($filename, 'a');
}
$this->size = filesize($filename) + $size;
}
}
/**
* 檢查目錄是否可寫
* @param string $path 目錄
* @return boolean
*/
protected function checkPath($path)
{
if (is_dir($path)) {
return true;
}
if (mkdir($path, 0755, true)) {
return true;
} else {
return false;
}
}
/**
* 析構方法,用于關閉文件資源
*/
public function __destruct()
{
$this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
}
}
```
- 課程介紹
- thinkphp5.0
- 安裝
- 開發規范
- 目錄結構
- 配置參數
- 系統常量
- tp5自帶的函數
- 助手函數
- 擴展類庫
- 基本類庫
- Workerman
- think-queue
- 驗證碼
- 圖片
- 權限認證
- 課前準備
- 數據庫設計
- 模塊設計
- 管理員管理
- 添加
- 編輯
- 刪除和批量刪除
- 列表頁
- 實列
- 權限管理
- 操作日志
- 基于行為的日記錄
- 行為日志的擴展
- 助手類庫
- 自建函數
- 將數組轉成uri字符串
- 獲取當前服務器的IP
- curl-post
- 截取文字中間的字符串
- 檢查中文姓名
- 省市區分別截取
- 抽獎概率問題
- 短信郵箱模板替換
- 生成csv
- PHP 圖片轉base64
- 銀行卡驗證
- json返回接口封裝
- 無限極分類
- 病毒
- xml和數組互轉
- xml轉成數組
- 數組轉xml
- tp控制器相關
- 獲取thinkph5下控制器和方法名
- 后臺查詢的簡單封裝
- 網址信息
- 獲取網站logo
- 判斷url是否存在
- 獲取title
- 判斷遠程文件是否存在
- 獲取頁面所有鏈接
- 過濾
- 截取
- 時間
- 獲取服務器信息
- 根據id生成唯一邀請碼
- 隨機顏色
- 數組字符串互換
- 創建多級目錄
- 懶人查詢
- 時間和時間戳轉換
- 房間id生菜
- 獲取需要的數組元素
- 文件和文件夾
- 文件類庫
- 文件夾
- 七牛云
- 七牛云運用場景
- 七牛云使用實例
- 郵箱
- 郵箱驗證
- 郵箱發送
- 數據庫
- 數據庫在thinkphp中的補充方法
- 備份和安全
- sql執行
- 數據庫備份2
- 時間日歷
- 時間格式化
- 日歷
- 圖片相關
- 自動獲取圖片主題顏色
- 獲取html中的圖片路徑
- 獲取圖片場景
- 獲取圖片實踐
- 圖片處理類
- 圖片處理場景
- 圖片處理實踐
- 數據驗證分析
- 身份證相關
- 新聞
- 自建類庫
- 簡易分類庫
- php 壓縮CSS代碼
- 身份證
- 分詞和抽詞
- 分詞應用場景
- 分詞實踐
- 中文轉拼音
- 中文轉拼音場景
- 中文轉拼音實踐
- 二維碼操作
- 二維碼場景
- 二維碼實踐
- 短地址
- PHPWord
- 插件化
- 插件擴展庫
- 插件列表
- 插件安裝和卸載
- 插件實踐
- 插件的離線安裝
- 計劃任務
- 計劃任務安裝
- 計劃任務實踐
- 定時器
- 注冊登錄
- 普通登錄注冊
- 第三方登錄注冊
- jwt接口登錄注冊
- 短信
- 飛鴿短信
- 阿里短信
- 消息隊列
- 網站地圖
- 全站靜態化
- 緩存
- 文件導出
- PDF生成
- phpword
- PHPExcel
- 其他類庫
- 百度
- 百度語音
- 快遞
- 跨域問題
- 寶塔
- 搜索記錄