86400) { return number_format($seconds / 86400, $precision).' days'; } elseif ($seconds > 3600) { return number_format($seconds / 3600, $precision).' hours'; } elseif ($seconds > 60) { return number_format($seconds / 60, $precision).' minutes'; } return number_format($seconds, $precision).' seconds'; } function FileSizeNiceDisplay($filesize, $precision=2) { if ($filesize < 1000) { $sizeunit = 'bytes'; $precision = 0; } else { $filesize /= 1024; $sizeunit = 'kB'; } if ($filesize >= 1000) { $filesize /= 1024; $sizeunit = 'MB'; } if ($filesize >= 1000) { $filesize /= 1024; $sizeunit = 'GB'; } return number_format($filesize, $precision).' '.$sizeunit; } function OutputInformation($id, $dhtml, $text='') { global $DHTMLenabled; if ($DHTMLenabled) { if (!is_null($dhtml)) { if ($id) { echo ''; } else { echo $dhtml; } flush(); } } else { if ($text) { echo $text; flush(); } } return true; } ///////////////////////////////////////////////////////////////////// /////////////////// END SUPPORT FUNCTIONS /////////////////// ///////////////////////////////////////////////////////////////////// if ((!defined('DB_HOST') || (DB_HOST == '')) || (!defined('DB_USER') || (DB_USER == '')) || (!defined('DB_PASS') || (DB_PASS == ''))) { echo '
'; echo 'database hostname:
'; echo 'database username:
'; echo 'database password:
'; echo ''; echo '
'; exit; } if (!@mysql_connect(DB_HOST, DB_USER, DB_PASS)) { die('There was a problem connecting to the database:
'."\n".mysql_error()); } if (!is_dir($backupabsolutepath)) { die('"'.htmlentities($backupabsolutepath).'" is not a directory'); } elseif (!is_writable($backupabsolutepath)) { die('"'.htmlentities($backupabsolutepath).'" is not writable'); } if ($SuppressHTMLoutput) { ob_start(); } echo '

backupDB() v'.backupDBversion.'

'; echo '

MySQL database backup

'; if (isset($_REQUEST['StartBackup'])) { OutputInformation('', 'Cancel

', 'Cancel

'); } OutputInformation('', '', 'DHTML display is disabled - you won\'t see anything until the backup is complete.'); flush(); $ListOfDatabasesToMaybeBackUp = array(); if (defined('DB_NAME')) { $ListOfDatabasesToMaybeBackUp[] = DB_NAME; } else { $db_name_list = mysql_list_dbs(); while (list($dbname) = mysql_fetch_array($db_name_list)) { $ListOfDatabasesToMaybeBackUp[] = $dbname; } } if (isset($_REQUEST['StartBackup']) && ($_REQUEST['StartBackup'] == 'partial')) { echo ''; echo '
'; foreach ($ListOfDatabasesToMaybeBackUp as $dbname) { $tables = mysql_list_tables($dbname); if (is_resource($tables)) { echo '
'.$dbname.'
'; $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 { if ($tablecounter++ >= TABLES_PER_COL) { echo ''; $tablecounter = 0; } $SQLquery = 'SELECT COUNT(*) AS num FROM '.$tablename; mysql_select_db($dbname); $result = mysql_query($SQLquery); $row = @mysql_fetch_array($result); echo ''.$tablename.' ('.$row['num'].')
'; } } } echo '

'; } } if (isset($_POST['DB_HOST'])) { echo ''; echo ''; echo ''; } echo ' '; echo ' '; echo ''; echo '
'; echo 'Back to menu'; } elseif (isset($_REQUEST['StartBackup'])) { if (($GZ_enabled && ($zp = @gzopen($backupabsolutepath.$tempbackupfilename, 'wb'))) || (!$GZ_enabled && ($fp = @fopen($backupabsolutepath.$tempbackupfilename, 'wb')))) { $fileheaderline = '# backupDB() v'.backupDBversion.' (http://www.silisoftware.com)'.LINE_TERMINATOR; $fileheaderline .= '# mySQL backup ('.date('F j, Y g:i a').') Type = '; if ($GZ_enabled) { gzwrite($zp, $fileheaderline, strlen($fileheaderline)); } else { fwrite($fp, $fileheaderline, strlen($fileheaderline)); } if ($_REQUEST['StartBackup'] == 'structure') { if ($GZ_enabled) { gzwrite($zp, 'Structure Only'.LINE_TERMINATOR.LINE_TERMINATOR, strlen('Structure Only'.LINE_TERMINATOR.LINE_TERMINATOR)); } else { fwrite($fp, 'Structure Only'.LINE_TERMINATOR.LINE_TERMINATOR, strlen('Structure Only'.LINE_TERMINATOR.LINE_TERMINATOR)); } $backuptype = 'full'; unset($SelectedTables); foreach ($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 { $SelectedTables[$dbname][] = $tablename; } } } } } } elseif (isset($_REQUEST['SelectedTables']) && is_array($_REQUEST['SelectedTables'])) { if ($GZ_enabled) { gzwrite($zp, 'Selected Tables Only'.LINE_TERMINATOR.LINE_TERMINATOR, strlen('Selected Tables Only'.LINE_TERMINATOR.LINE_TERMINATOR)); } else { fwrite($fp, 'Selected Tables Only'.LINE_TERMINATOR.LINE_TERMINATOR, strlen('Selected Tables Only'.LINE_TERMINATOR.LINE_TERMINATOR)); } $backuptype = 'partial'; $SelectedTables = $_REQUEST['SelectedTables']; } else { if ($GZ_enabled) { gzwrite($zp, 'Complete'.LINE_TERMINATOR.LINE_TERMINATOR, strlen('Complete'.LINE_TERMINATOR.LINE_TERMINATOR)); } else { fwrite($fp, 'Complete'.LINE_TERMINATOR.LINE_TERMINATOR, strlen('Complete'.LINE_TERMINATOR.LINE_TERMINATOR)); } $backuptype = 'full'; unset($SelectedTables); foreach ($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 { $SelectedTables[$dbname][] = $tablename; } } } } } } $starttime = getmicrotime(); OutputInformation('', null, 'Checking tables...

'); $TableErrors = array(); foreach ($SelectedTables as $dbname => $selectedtablesarray) { mysql_select_db($dbname); $repairresult = ''; $CanContinue = true; foreach ($selectedtablesarray as $selectedtablename) { OutputInformation('statusinfo', 'Checking table '.$dbname.'.'.$selectedtablename.''); $result = mysql_query('CHECK TABLE '.$selectedtablename); while ($row = mysql_fetch_array($result)) { set_time_limit(60); if ($row['Msg_text'] == 'OK') { mysql_query('OPTIMIZE TABLE '.$selectedtablename); } else { OutputInformation('statusinfo', 'Repairing table '.$selectedtablename.''); $repairresult .= 'REPAIR TABLE '.$selectedtablename.' EXTENDED'."\n\n"; $fixresult = mysql_query('REPAIR TABLE '.$selectedtablename.' EXTENDED'); $ThisCanContinue = false; while ($fixrow = mysql_fetch_array($fixresult)) { $thisMessage = $fixrow['Msg_type'].': '.$fixrow['Msg_text']; $repairresult .= $thisMessage."\n"; switch ($thisMessage) { case 'status: OK': case 'error: The handler for the table doesn\'t support repair': $ThisCanContinue = true; break; } } if (!$ThisCanContinue) { $CanContinue = false; } $repairresult .= "\n\n".str_repeat('-', 60)."\n\n"; } } } if (!empty($repairresult)) { echo '
'.$repairresult.'
'; if (!$CanContinue) { if ($SuppressHTMLoutput) { ob_end_clean(); echo 'errors'; } exit; } } } OutputInformation('statusinfo', ''); OutputInformation('', '
Overall Progress:
'); $overallrows = 0; foreach ($SelectedTables as $dbname => $value) { mysql_select_db($dbname); echo '
'.$dbname.'
'; $tablecounter = 0; for ($t = 0; $t < count($SelectedTables[$dbname]); $t++) { if ($tablecounter++ >= TABLES_PER_COL) { echo ''; $tablecounter = 1; } $SQLquery = 'SELECT COUNT(*) AS num FROM '.$SelectedTables[$dbname][$t]; $result = mysql_query($SQLquery); $row = mysql_fetch_array($result); $rows[$t] = $row['num']; $overallrows += $rows[$t]; echo ''.$SelectedTables[$dbname][$t].' ('.number_format($rows[$t]).' records)
'; } echo '

'; } $alltablesstructure = ''; foreach ($SelectedTables as $dbname => $value) { mysql_select_db($dbname); for ($t = 0; $t < count($SelectedTables[$dbname]); $t++) { set_time_limit(60); OutputInformation('statusinfo', 'Creating structure for '.$dbname.'.'.$SelectedTables[$dbname][$t].''); $fieldnames = array(); $structurelines = array(); $result = mysql_query('SHOW FIELDS FROM '.BACKTICKCHAR.$SelectedTables[$dbname][$t].BACKTICKCHAR); while ($row = mysql_fetch_array($result)) { $structureline = BACKTICKCHAR.$row['Field'].BACKTICKCHAR; $structureline .= ' '.$row['Type']; $structureline .= ' '.($row['Null'] ? '' : 'NOT ').'NULL'; eregi('^[a-z]+', $row['Type'], $matches); $RowTypes[$dbname][$SelectedTables[$dbname][$t]][$row['Field']] = $matches[0]; if (@$row['Default']) { if (eregi('^(tiny|medium|long)?(text|blob)', $row['Type'])) { // no default values } else { $structureline .= ' default \''.$row['Default'].'\''; } } $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.$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($SelectedTables[$dbname][$t]).'"'); if (!($TableStatusRow = mysql_fetch_array($TableStatusResult))) { die('failed to execute "SHOW TABLE STATUS" on '.$dbname.'.'.$tablename); } $tablestructure = 'CREATE TABLE '.($CreateIfNotExists ? 'IF NOT EXISTS ' : '').($dbNameInCreate ? BACKTICKCHAR.$dbname.BACKTICKCHAR.'.' : '').BACKTICKCHAR.$SelectedTables[$dbname][$t].BACKTICKCHAR.' ('.LINE_TERMINATOR; $tablestructure .= ' '.implode(','.LINE_TERMINATOR.' ', $structurelines).LINE_TERMINATOR; $tablestructure .= ') TYPE='.(@$TableStatusRow['Engine'] ? $TableStatusRow['Engine'] : $TableStatusRow['Type']); // MySQL 4.and higher, the 'Type' of database is now '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 } if ($GZ_enabled) { gzwrite($zp, $alltablesstructure.LINE_TERMINATOR, strlen($alltablesstructure) + strlen(LINE_TERMINATOR)); } else { fwrite($fp, $alltablesstructure.LINE_TERMINATOR, strlen($alltablesstructure) + strlen(LINE_TERMINATOR)); } OutputInformation('statusinfo', ''); if ($_REQUEST['StartBackup'] != 'structure') { $processedrows = 0; foreach ($SelectedTables as $dbname => $value) { set_time_limit(60); mysql_select_db($dbname); for ($t = 0; $t < count($SelectedTables[$dbname]); $t++) { $result = mysql_query('SELECT * FROM '.$SelectedTables[$dbname][$t]); $rows[$t] = mysql_num_rows($result); if ($rows[$t] > 0) { $tabledatadumpline = '# dumping data for '.$dbname.'.'.$SelectedTables[$dbname][$t].LINE_TERMINATOR; if ($GZ_enabled) { gzwrite($zp, $tabledatadumpline, strlen($tabledatadumpline)); } else { fwrite($fp, $tabledatadumpline, strlen($tabledatadumpline)); } } unset($fieldnames); for ($i = 0; $i < mysql_num_fields($result); $i++) { $fieldnames[] = mysql_field_name($result, $i); } if ($_REQUEST['StartBackup'] == 'complete') { $insertstatement = ($ReplaceInto ? 'REPLACE' : 'INSERT').' INTO '.BACKTICKCHAR.$SelectedTables[$dbname][$t].BACKTICKCHAR.' ('.BACKTICKCHAR.implode(BACKTICKCHAR.', '.BACKTICKCHAR, $fieldnames).BACKTICKCHAR.') VALUES ('; } else { $insertstatement = ($ReplaceInto ? 'REPLACE' : 'INSERT').' INTO '.BACKTICKCHAR.$SelectedTables[$dbname][$t].BACKTICKCHAR.' VALUES ('; } $currentrow = 0; $thistableinserts = ''; while ($row = mysql_fetch_array($result)) { unset($valuevalues); foreach ($fieldnames as $key => $val) { if ($row[$key] === null) { $valuevalues[] = 'NULL'; } else { switch ($RowTypes[$dbname][$SelectedTables[$dbname][$t]][$val]) { // binary data dump, two hex characters per byte case 'tinyblob': case 'blob': case 'mediumblob': case 'longblob': if ($HexBLOBs) { $data = $row[$key]; $data_len = strlen($data); $hexstring = '0x'; for ($i = 0; $i < $data_len; $i++) { $hexstring .= str_pad(dechex(ord($data{$i})), 2, '0', STR_PAD_LEFT); } $valuevalues[] = $hexstring; } else { $valuevalues[] = QUOTECHAR.mysql_escape_string($row[$key]).QUOTECHAR; } break; // just the (numeric) value, not surrounded by quotes case 'tinyint': case 'smallint': case 'mediumint': case 'int': case 'bigint': case 'float': case 'double': case 'decimal': case 'year': $valuevalues[] = mysql_escape_string($row[$key]); break; // value surrounded by quotes case 'varchar': case 'char': case 'tinytext': case 'text': case 'mediumtext': case 'longtext': case 'enum': case 'set': case 'date': case 'datetime': case 'time': case 'timestamp': default: $valuevalues[] = QUOTECHAR.mysql_escape_string($row[$key]).QUOTECHAR; break; } } } $thistableinserts .= $insertstatement.implode(', ', $valuevalues).');'.LINE_TERMINATOR; if (strlen($thistableinserts) >= BUFFER_SIZE) { if ($GZ_enabled) { gzwrite($zp, $thistableinserts, strlen($thistableinserts)); } else { fwrite($fp, $thistableinserts, strlen($thistableinserts)); } $thistableinserts = ''; } if ((++$currentrow % STATS_INTERVAL) == 0) { set_time_limit(60); if ($DHTMLenabled) { OutputInformation('rows_'.$dbname.'_'.$SelectedTables[$dbname][$t], ''.$SelectedTables[$dbname][$t].' ('.number_format($rows[$t]).' records, ['.number_format(($currentrow / $rows[$t])*100).'%])'); $elapsedtime = getmicrotime() - $starttime; $percentprocessed = ($processedrows + $currentrow) / $overallrows; $overallprogress = 'Overall Progress: '.number_format($processedrows + $currentrow).' / '.number_format($overallrows).' ('.number_format($percentprocessed * 100, 1).'% done) ['.FormattedTimeRemaining($elapsedtime).' elapsed'; if (($percentprocessed > 0) && ($percentprocessed < 1)) { $overallprogress .= ', '.FormattedTimeRemaining(abs($elapsedtime - ($elapsedtime / $percentprocessed))).' remaining'; } $overallprogress .= ']'; OutputInformation('topprogress', $overallprogress); } } } if ($DHTMLenabled) { OutputInformation('rows_'.$dbname.'_'.$SelectedTables[$dbname][$t], $SelectedTables[$dbname][$t].' ('.number_format($rows[$t]).' records, [100%])'); $processedrows += $rows[$t]; } if ($GZ_enabled) { gzwrite($zp, $thistableinserts.LINE_TERMINATOR.LINE_TERMINATOR, strlen($thistableinserts) + strlen(LINE_TERMINATOR) + strlen(LINE_TERMINATOR)); } else { fwrite($fp, $thistableinserts.LINE_TERMINATOR.LINE_TERMINATOR, strlen($thistableinserts) + strlen(LINE_TERMINATOR) + strlen(LINE_TERMINATOR)); } } } } if ($GZ_enabled) { gzclose($zp); } else { fclose($fp); } if ($_REQUEST['StartBackup'] == 'structure') { $newfullfilename = $backupabsolutepath.$strubackupfilename; } elseif ($backuptype == 'full') { $newfullfilename = $backupabsolutepath.$fullbackupfilename; } else { $newfullfilename = $backupabsolutepath.$partbackupfilename; } if (file_exists($newfullfilename)) { unlink($newfullfilename); // Windows won't allow overwriting via rename } rename($backupabsolutepath.$tempbackupfilename, $newfullfilename); if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { touch($newfullfilename); if (!chmod($newfullfilename, 0777)) { } } echo '
Backup complete in '.FormattedTimeRemaining(getmicrotime() - $starttime, 2).'.
'; echo ''.basename($newfullfilename).' ('.FileSizeNiceDisplay(filesize($newfullfilename), 2); echo ')

Back to MySQL Database Backup main menu
'; OutputInformation('cancellink', ''); } else { echo 'Warning: failed to open '.$backupabsolutepath.$tempbackupfilename.' for writing!

'; if (is_dir($backupabsolutepath)) { echo 'CHMOD 777 on the directory ('.htmlentities($backupabsolutepath).') should fix that.'; } else { echo 'The specified directory does not exist: "'.htmlentities($backupabsolutepath).'"'; } } } else { // !$_REQUEST['StartBackup'] if (file_exists($backupabsolutepath.$fullbackupfilename)) { echo 'It is now '.gmdate('F j, Y g:ia T', time() + date('Z')).'
'; echo 'Last full backup of MySQL databases: '; $lastbackuptime = filemtime($backupabsolutepath.$fullbackupfilename); echo gmdate('F j, Y g:ia T', $lastbackuptime + date('Z')); echo ' ('.FormattedTimeRemaining(time() - $lastbackuptime).' ago)
'; if ((time() - $lastbackuptime) < 86400) { echo 'Generally, backing up more than once a day is not neccesary.
'; } echo '
Download previous full backup ('.FileSizeNiceDisplay(filesize($backupabsolutepath.$fullbackupfilename), 2).') (right-click, Save As...)

'; } else { echo 'Last backup of MySQL databases: unknown'.($backuptimestamp ? ' (incompatible with timestamping)' : '').'
'; } $BackupTypesList = array( 'complete' => 'Full backup, complete inserts (recommended)', 'standard' => 'Full backup, standard inserts (smaller)', 'partial' => 'Selected tables only (with complete inserts)', 'structure' => 'Table structure(s) only' ); echo '
'; if (isset($_POST['DB_HOST'])) { echo ''; echo ''; echo ''; } echo '
'; echo ''; echo '
'; } if ($SuppressHTMLoutput) { ob_end_clean(); echo "File saved to $backupabsolutepath.$fullbackupfilename."; } if ($CloseWindowOnFinish) { // Auto close the browser after the script finishes. // This will allow task scheduler in Windows to work properly, // else the task will be considered running until the browser is closed echo ''; } ?>