⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 backup.php

📁 网络硬盘_支持1GB文件上传和续传_无错版
💻 PHP
📖 第 1 页 / 共 2 页
字号:
<?
/*
+--------------------------------------------------------------------------
|   Mega File Hosting Script v1.2
|   ========================================
|   by Stephen Yabziz
|   (c) 2005-2006 YABSoft Services
|   http://www.yabsoft.com
|   ========================================
|   Web: http://www.yabsoft.com
|   Email: ywyhnchina@163.com
+--------------------------------------------------------------------------
|
|   > Script written by Stephen Yabziz
|   > Date started: 1th March 2006
+--------------------------------------------------------------------------
*/
class BackUp
{
    var $DB_HOST='localhost';
    var $DB_USER=null;
    var $DB_PASS=null;

    var $SelectedTables=array();
    var $BackupType=null;
    var $BackupDir=null;
    var $ListOfDatabasesToMaybeBackUp=array();
    var $GZ_enabled=null;
    
    var $debug=false;
    
    function BackUp($host='localhost',$user='root',$pass='')
    {
        define('backupDBversion', '1.1.27a');
        define('BACKTICKCHAR',    '`');
        define('QUOTECHAR',       '\'');
        define('LINE_TERMINATOR', "\n");  // \n = UNIX; \r\n = Windows; \r = Mac
        define('BUFFER_SIZE',     32768); // in bytes

        $starttime = $this->getmicrotime();
        
        $this->DB_HOST=$host;
        $this->DB_USER=$user;
        $this->DB_PASS=$pass;

        if($this->GZ_enabled==null)
        $this->GZ_enabled         = (bool) function_exists('gzopen');
        
        $this->tempbackupfilename = 'db_backup.temp.sql'.($this->GZ_enabled ? '.gz' : '');
        if (!@mysql_connect($this->DB_HOST, $this->DB_USER, $this->DB_PASS)) {
	        die('There was a problem connecting to the database:<br>'."\n".mysql_error());
        }

    }
    function AddDatabase($dbname='')
    {
        if($dbname) $this->ListOfDatabasesToMaybeBackUp[] = $dbname;
        else
        {
            $db_name_list = mysql_list_dbs();
	        while (list($dbname) = mysql_fetch_array($db_name_list))
		       $this->ListOfDatabasesToMaybeBackUp[] = $dbname;
        }
    }
    function AddTable($dbname='',$table)
    {
        if($dbname&&$table) $this->SelectedTables[$dbname][] = $table;
    }
    function Start($stucture,$data,$complete)
    {
        if($stucture==1) $this->BackupType='_stucture';
        if($data==1) $this->BackupType.='_data';
        if($data==1&&$complete==1) $this->BackupType.='_complete';
        
        $this->DataType=$complete;
        
        $this->GetBackupTables();
        $this->CheckStatus();
        
        if($stucture==1)
        $this->BackupStucture();
        
        if($data==1)
        $this->BackupData();
    }
    function Store($tofile='')
    {
        $this->CloseFile();
        
        $backuptimestamp    = '.'.date('Y-m-d'); // timestamp
        if (!empty($this->DB_NAME)) {
	        $backuptimestamp = '.'.$this->DB_NAME.$backuptimestamp;
        }
        
        if($tofile=='')
        {
            $this->backupfilename = 'db'.$this->BackupType.'_'.$backuptimestamp.'.sql'.($this->GZ_enabled ? '.gz' : '');
        }
        else
        $this->backupfilename=$tofile;
        
        if (file_exists($this->BackupDir.$this->backupfilename)) {
			unlink($this->BackupDir.$this->backupfilename); // Windows won't allow overwriting via rename
		}
		rename($this->BackupDir.$this->tempbackupfilename, $this->BackupDir.$this->backupfilename);
    }
    function Email()
    {
        if ($fp = @fopen($this->BackupDir.$this->backupfilename, 'rb')) {
			$emailattachmentfiledata = fread($fp, filesize($this->BackupDir.$this->backupfilename));
			fclose($fp);
			if (!$this->EmailAttachment($this->admin_email, $this->admin_email, 'backupDB: '.basename($this->backupfilename), 'backupDB: '.basename($this->backupfilename), $emailattachmentfiledata, basename($this->backupfilename))) {
				mail($this->admin_email, 'backupDB: Failed to email attachment ['.basename($this->backupfilename).']', 'Failed to email attachment ['.basename($this->backupfilename).']');
			}
			unset($emailattachmentfiledata);
		}
    }
    function FTP()
    {

    }
    function GetBackupTables()
    {
        $NeverBackupDBtypes = array('HEAP');
        //get table from db
        foreach ($this->ListOfDatabasesToMaybeBackUp as $dbname) {
			set_time_limit(60);
			$tables = mysql_list_tables($dbname);
			if (is_resource($tables)) {
				$tablecounter = 0;
				while (list($tablename) = mysql_fetch_array($tables)) {
					$TableStatusResult = mysql_query('SHOW TABLE STATUS LIKE "'.mysql_escape_string($tablename).'"');
					if ($TableStatusRow = mysql_fetch_array($TableStatusResult)) {
						if (in_array($TableStatusRow['Type'], $NeverBackupDBtypes)) {

							// no need to back up HEAP tables, and will generate errors if you try to optimize/repair

						} else {

							$this->SelectedTables[$dbname][] = $tablename;
						}
					}
				}
			}
		}
    }
    /**
    Check table status,repair it,if nessesary,Repair table
    */
    function CheckStatus()
    {
        if(count($this->SelectedTables)==0) die("No table selected to backup");
		$this->OutputInformation('Checking tables...');
		$TableErrors = array();
		foreach ($this->SelectedTables as $dbname => $selectedtablesarray) {
		mysql_select_db($dbname);
		$repairresult = '';
		$CanContinue = true;
		foreach ($selectedtablesarray as $selectedtablename) {

			$this->OutputInformation('Checking table <b>'.$dbname.'.'.$selectedtablename.'</b>');
			$result = mysql_query('CHECK TABLE '.BACKTICKCHAR.$selectedtablename.BACKTICKCHAR);
			while ($row = mysql_fetch_array($result)) {
				set_time_limit(60);
				if ($row['Msg_text'] == 'OK') {
                    $this->OutputInformation('Optimize table <b>'.$dbname.'.'.$selectedtablename.'</b>');
					mysql_query('OPTIMIZE TABLE '.$selectedtablename);

				} else {

					$this->OutputInformation('Repairing table <b>'.$selectedtablename.'</b>');
					$repairresult .= 'REPAIR TABLE '.$selectedtablename.' EXTENDED'."\n\n";
					$fixresult = mysql_query('REPAIR TABLE '.BACKTICKCHAR.$selectedtablename.BACKTICKCHAR.' EXTENDED');
					$ThisCanContinue = false;
					while ($fixrow = mysql_fetch_array($fixresult)) {
						$repairresult .= $fixrow['Msg_type'].': '.$fixrow['Msg_text']."\n";
						if (($fixrow['Msg_type'] == 'status') && ($fixrow['Msg_text'] == 'OK')) {
							$ThisCanContinue = true;
						}
					}
					if (!$ThisCanContinue) {
						$CanContinue = false;
					}

					$repairresult .= "\n\n".str_repeat('-', 60)."\n\n";

				}
			}
		}
        }
    }
    /**
    Backup selected table stucture
    $this->SelectedTables get from $this->GetBackupTables
    */
    function BackupStucture()
    {
        if(count($this->SelectedTables)==0) die("No table selected to backup");
        $alltablesstructure = '';
        foreach ($this->SelectedTables as $dbname => $value) {
		mysql_select_db($dbname);
        $table_num= count($this->SelectedTables[$dbname]);
		for ($t = 0; $t < $table_num; $t++) {
			set_time_limit(60);
			$this->OutputInformation('Creating structure for <b>'.$dbname.'.'.$this->SelectedTables[$dbname][$t].'</b>');

			$fieldnames     = array();
			$structurelines = array();
			$result = mysql_query('SHOW FIELDS FROM '.BACKTICKCHAR.$this->SelectedTables[$dbname][$t].BACKTICKCHAR);
			while ($row = mysql_fetch_array($result)) {
				$structureline  = BACKTICKCHAR.$row['Field'].BACKTICKCHAR;
				$structureline .= ' '.$row['Type'];
				$structureline .= ' '.($row['Null'] ? '' : 'NOT ').'NULL';
				if (isset($row['Default'])) {
					switch ($row['Type']) {
						case 'tinytext':
						case 'tinyblob':
						case 'text':
						case 'blob':
						case 'mediumtext':
						case 'mediumblob':
						case 'longtext':
						case 'longblob':
							// no default values
							break;
						default:
							$structureline .= ' default \''.$row['Default'].'\'';
							break;
					}
				}
				$structureline .= ($row['Extra'] ? ' '.$row['Extra'] : '');
				$structurelines[] = $structureline;

				$fieldnames[] = $row['Field'];
			}
			mysql_free_result($result);

			$tablekeys    = array();
			$uniquekeys   = array();
			$fulltextkeys = array();
			$result = mysql_query('SHOW KEYS FROM '.BACKTICKCHAR.$this->SelectedTables[$dbname][$t].BACKTICKCHAR);
			while ($row = mysql_fetch_array($result)) {
				$uniquekeys[$row['Key_name']]   = (bool) ($row['Non_unique'] == 0);
				if (isset($row['Index_type'])) {
					$fulltextkeys[$row['Key_name']] = (bool) ($row['Index_type'] == 'FULLTEXT');
				} elseif (@$row['Comment'] == 'FULLTEXT') {
					$fulltextkeys[$row['Key_name']] = true;
				} else {
					$fulltextkeys[$row['Key_name']] = false;
				}
				$tablekeys[$row['Key_name']][$row['Seq_in_index']] = $row['Column_name'];
				ksort($tablekeys[$row['Key_name']]);
			}
			mysql_free_result($result);
			foreach ($tablekeys as $keyname => $keyfieldnames) {
				$structureline  = '';
				if ($keyname == 'PRIMARY') {
					$structureline .= 'PRIMARY KEY';
				} else {
					if ($fulltextkeys[$keyname]) {
						$structureline .= 'FULLTEXT ';
					} elseif ($uniquekeys[$keyname]) {
						$structureline .= 'UNIQUE ';
					}
					$structureline .= 'KEY '.BACKTICKCHAR.$keyname.BACKTICKCHAR;
				}
				$structureline .= ' ('.BACKTICKCHAR.implode(BACKTICKCHAR.','.BACKTICKCHAR, $keyfieldnames).BACKTICKCHAR.')';
				$structurelines[] = $structureline;
			}


			$TableStatusResult = mysql_query('SHOW TABLE STATUS LIKE "'.mysql_escape_string($this->SelectedTables[$dbname][$t]).'"');
			if (!($TableStatusRow = mysql_fetch_array($TableStatusResult))) {
				die('failed to execute "SHOW TABLE STATUS" on '.$dbname.'.'.$tablename);
			}

			$tablestructure  = 'CREATE TABLE '.BACKTICKCHAR.$dbname.BACKTICKCHAR.'.'.BACKTICKCHAR.$this->SelectedTables[$dbname][$t].BACKTICKCHAR.' ('.LINE_TERMINATOR;
            $tablestructure  = 'CREATE TABLE '.BACKTICKCHAR.$this->SelectedTables[$dbname][$t].BACKTICKCHAR.' ('.LINE_TERMINATOR;
			$tablestructure .= '  '.implode(','.LINE_TERMINATOR.'  ', $structurelines).LINE_TERMINATOR;
			$tablestructure .= isset($TableStatusRow['Type']) ? ') TYPE='.$TableStatusRow['Type']:(isset($TableStatusRow['Engine']) ? ') Engine='.$TableStatusRow['Engine']:')');

			if ($TableStatusRow['Auto_increment'] !== null) {
				$tablestructure .= ' AUTO_INCREMENT='.$TableStatusRow['Auto_increment'];
			}
			$tablestructure .= ';'.LINE_TERMINATOR.LINE_TERMINATOR;

			$alltablesstructure .= str_replace(' ,', ',', $tablestructure);

		} // end table structure backup
        }
        $this->OpenFile();
        $this->Write2File($alltablesstructure);
        return $alltablesstructure;
    }
    /**
    Backup selected table data
    $this->SelectedTables get from $this->GetBackupTables
    */
    function  BackupData()
    {
        if(count($this->SelectedTables)==0) die("No table selected to backup");
        $this->OpenFile();
        $processedrows = 0;
        $alltablesdata = '';
		foreach ($this->SelectedTables as $dbname => $value) {
			set_time_limit(60);
			mysql_select_db($dbname);
			for ($t = 0; $t < count($this->SelectedTables[$dbname]); $t++) {
                $this->OutputInformation('Creating data for table <b>'.$dbname.'.'.$this->SelectedTables[$dbname][$t].'</b>');

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -