Here is an inline example:
helping in development of all class code
- Dylan Pugh for precious advices halfing the size of the output file and for helping in debug
$connection = @mysql_connect($dbhost,$dbuser,$dbpsw);
$dumper = new MySQLDump($dbname,'filename.sql',false,false);
$dumper->doDump();
Special thanks to:
- Andrea Ingaglio protected function dumpDb($filename) { $this->log('Dumping databases'); $user = Config::get($this->local, 'user'); $pass = Config::get($this->local, 'pass'); $dumper = new MySQLDump('localhost', $user, $pass); $dbs = $dumper->listDbs(); // $this->log('Databases: %s', implode(', ', $dbs)); $zip = new ZipArchive(); $zip->open($filename, ZIPARCHIVE::CREATE); foreach ($dbs as $db) { if (empty($db)) { continue; } $this->log('Dump db %s', $db); $dump = $dumper->dumpDatabase($db); $ext = '.sql'; if (function_exists('gzencode')) { $dump = gzencode($dump, 9); $ext .= '.gz'; } $zip->addFromString($db . $ext, $dump); } $this->log('Dump Finished'); $this->log('Zipped Files: %s', $zip->numFiles); $zip->close(); }
function dump($argv, $argc) { global $fold, $database, $site; $fix = $argv[1]; $datestamp = date("Y-m-d_H-i-s"); $dumpFileName = /* $page['base']['href'] . */ $fold['sql'] . $database['name'] . "_$datestamp.sql"; $connection = mysql_connect($database['host'], $database['user'], $database['pass']); if (!$connection) { return "Святые одуванчики! У нас проблемы!"; } include_once $fold['classes'] . 'MySQLDump' . $site['extensions']; $dumper = new MySQLDump($database['name'], $dumpFileName, false, false); mysql_query("set names utf8"); $dumper->doDump(); if ($fix) { # фикс заменяющий неработающую CURRENT_TIMESTAMP на некоторых серверах (в частности на сервере ФС) $fileContents = file_get_contents($dumpFileName); $fileContents = str_ireplace('CURRENT_TIMESTAMP', date("Y-m-d H:i:s"), $fileContents); file_put_contents($dumpFileName, $fileContents); } return "Дамп ${mysql['db']}_$datestamp.sql успешно создан в папку дампов и бекапов \"".$fold['sql']."\". Просмотр содержимого: `get last dump`. Создание дампа с просмотром осуществляется командой get mysql dump.\n"; }
private function _dumpDatabase($filename, $dbname, $droptable) { $filename .= ".sql"; $filename = $this->folder . DIRECTORY_SEPARATOR . $filename; $dbconfigList = BizSystem::getConfiguration()->getDatabaseInfo(); $dbconfig = $dbconfigList[$dbname]; if (strtolower($dbconfig["Driver"]) != 'pdo_mysql') { return; } include_once dirname(dirname(__FILE__)) . "/lib/MySQLDump.class.php"; $backup = new MySQLDump(); if ($droptable == 1) { $backup->droptableifexists = true; } else { $backup->droptableifexists = false; } if ($dbconfig["Port"]) { $dbHost = $dbconfig["Server"] . ":" . $dbconfig["Port"]; } else { $dbHost = $dbconfig["Port"]; } $dbc = $backup->connect($dbHost, $dbconfig["User"], $dbconfig["Password"], $dbconfig["DBName"], $dbconfig["Charset"]); if (!$dbc) { echo $backup->mysql_error; } $backup->dump(); $data = $backup->output; file_put_contents($filename, $data); @chmod($filename, 0777); return $filename; }
protected function execute(InputInterface $input, OutputInterface $output) { $host = $input->getOption('host'); $user = $input->getOption('user'); $pass = $input->getOption('pass'); $dbName = $input->getArgument('name'); try { $this->dump = $this->pdoFactory->makeDump($host, $user, $pass, $dbName); } catch (\PDOException $e) { throw new RuntimeException('Error while connecting to database [' . $dbName . ']: ' . $e->getMessage()); } if (false === $this->dump) { $output->writeln('<error>Something went wrong with the dump component instance.</error>'); return false; } \Codeception\Configuration::config(); if (!empty($input->getOption('dump-file'))) { $dumpFile = $input->getOption('dump-file'); } else { $dumpFile = codecept_data_dir($input->getArgument('snapshot') . '.sql'); } $output->writeln('<info>Dump file will be written to [' . $dumpFile . ']</info>'); if (!empty($input->getOption('dist-dump-file'))) { $distDumpFile = $input->getOption('dist-dump-file'); } else { $distDumpFile = codecept_data_dir($input->getArgument('snapshot') . '.dist.sql'); } $output->writeln('<info>Distribution version of dump file will be written to [' . $distDumpFile . ']</info>'); $skipTables = $input->getOption('skip-tables'); if (!empty($skipTables)) { $tables = explode(',', $skipTables); foreach ($tables as $table) { $this->dump->tables[$table] = \MySQLDump::NONE; } } $memory = fopen('php://memory', 'w'); $this->dump->write($memory); rewind($memory); $dumpContents = stream_get_contents($memory); if (!$this->filesystem->file_put_contents($dumpFile, $dumpContents)) { $output->writeln('<error>Could not write dump to [' . $dumpFile . ']</error>'); return false; } $output->writeln('<info>Dump file written to [' . $dumpFile . ']</info>'); $localUrl = $input->getOption('local-url'); $distUrl = $input->getOption('dist-url'); $localDomain = rtrim(preg_replace('~http(s)*:\\/\\/(www\\.)*~', '', $localUrl), '/'); $distDomain = rtrim(preg_replace('~http(s)*:\\/\\/(www\\.)*~', '', $distUrl), '/'); $distDumpContents = str_replace($localDomain, $distDomain, $dumpContents); if (!$this->filesystem->file_put_contents($distDumpFile, $distDumpContents)) { $output->writeln('<error>Could not write dist dump to [' . $distDumpFile . ']</error>'); return false; } $output->writeln('<info>Distribution version of dump file written to [' . $distDumpFile . ']</info>'); $output->writeln('<comment>Any occurrence of [' . $localDomain . '] in it was replaced with [' . $distDomain . ']</comment>'); parent::execute($input, $output); return true; }
/** * Run the task, and do the business * * @param SS_HTTPRequest $httpRequest */ function run($httpRequest) { global $databaseConfig; // environment type Director::set_environment_type("dev"); // debug ini_set("display_errors", "2"); ERROR_REPORTING(E_ALL); /* $dbhost = $databaseConfig['server']; $dbuser = $databaseConfig['username']; $dbpwd = $databaseConfig['password']; $dbname = $databaseConfig['database']; $backupfolder = $_SERVER['DOCUMENT_ROOT'].'/db_backups'; $dumpfile = $backupfolder."/".$dbname."_".date("Y-m-d_H-i-s").".sql"; if (!is_dir($backupfolder)) mkdir($backupfolder); passthru("/usr/bin/mysqldump --opt --host=$dbhost --user=$dbuser --password=$dbpwd $dbname > $dumpfile"); echo "Created: ".$dumpfile; passthru("tail -1 $dumpfile"); */ $drop_table_if_exists = false; //Add MySQL 'DROP TABLE IF EXISTS' Statement To Output $dbhost = $databaseConfig['server']; $dbuser = $databaseConfig['username']; $dbpass = $databaseConfig['password']; $dbname = $databaseConfig['database']; $backupfolder = __DIR__ . '/../../db_backups'; $dumpfile = $backupfolder . "/" . $dbname . "_" . date("Y-m-d_H-i-s") . ".sql"; $backup = new MySQLDump(); $backup->droptableifexists = $drop_table_if_exists; $backup->connect($dbhost, $dbuser, $dbpass, $dbname); //Connect To Database if (!$backup->connected) { die('Error: ' . $backup->mysql_error); } //On Failed Connection, Show Error. $backup->list_tables(); //List Database Tables. $broj = count($backup->tables); //Count Database Tables. $output = ''; echo "found " . $broj . " tables \n\n"; for ($i = 0; $i < $broj; $i++) { $table_name = $backup->tables[$i]; //Get Table Names. $backup->dump_table($table_name); //Dump Data to the Output Buffer. $output .= $backup->output; } if (!is_dir($backupfolder)) { mkdir($backupfolder); } file_put_contents($dumpfile, $output); echo "Dumped into " . $dumpfile; //echo "<pre>".$output."</pre>"; }
private function __export() { $sql_schema = $sql_data = NULL; require_once dirname(__FILE__) . '/lib/class.mysqldump.php'; $dump = new MySQLDump($this->_Parent->Database); $tables = array('tbl_authors', 'tbl_cache', 'tbl_entries', 'tbl_extensions', 'tbl_extensions_delegates', 'tbl_fields', 'tbl_fields_%', 'tbl_forgotpass', 'tbl_pages', 'tbl_pages_types', 'tbl_sections', 'tbl_sections_association'); ## Grab the schema foreach ($tables as $t) { $sql_schema .= $dump->export($t, MySQLDump::STRUCTURE_ONLY); } $sql_schema = str_replace('`' . $this->_Parent->Configuration->get('tbl_prefix', 'database'), '`tbl_', $sql_schema); $sql_schema = preg_replace('/AUTO_INCREMENT=\\d+/i', '', $sql_schema); $tables = array('tbl_entries', 'tbl_extensions', 'tbl_extensions_delegates', 'tbl_fields', 'tbl_pages', 'tbl_pages_types', 'tbl_sections', 'tbl_sections_association'); ## Field data and entry data schemas needs to be apart of the workspace sql dump $sql_data = $dump->export('tbl_fields_%', MySQLDump::ALL); $sql_data .= $dump->export('tbl_entries_%', MySQLDump::ALL); ## Grab the data foreach ($tables as $t) { $sql_data .= $dump->export($t, MySQLDump::DATA_ONLY); } $sql_data = str_replace('`' . $this->_Parent->Configuration->get('tbl_prefix', 'database'), '`tbl_', $sql_data); $config_string = NULL; $config = $this->_Parent->Configuration->get(); unset($config['symphony']['build']); unset($config['symphony']['cookie_prefix']); unset($config['general']['useragent']); unset($config['file']['write_mode']); unset($config['directory']['write_mode']); unset($config['database']['host']); unset($config['database']['port']); unset($config['database']['user']); unset($config['database']['password']); unset($config['database']['db']); unset($config['database']['tbl_prefix']); unset($config['region']['timezone']); foreach ($config as $group => $set) { foreach ($set as $key => $val) { $config_string .= "\t\t\$conf['" . $group . "']['" . $key . "'] = '" . $val . "';" . self::CRLF; } } $install_template = str_replace(array('<!-- BUILD -->', '<!-- VERSION -->', '<!-- ENCODED SQL SCHEMA DUMP -->', '<!-- ENCODED SQL DATA DUMP -->', '<!-- CONFIGURATION -->'), array($this->_Parent->Configuration->get('build', 'symphony'), $this->_Parent->Configuration->get('version', 'symphony'), base64_encode($sql_schema), base64_encode($sql_data), trim($config_string)), file_get_contents(dirname(__FILE__) . '/lib/installer.tpl')); $archive = new ZipArchive(); $res = $archive->open(TMP . '/install.tmp.zip', ZipArchive::CREATE); if ($res === TRUE) { $archive->addFromString('workspace/install.sql', $sql_data); } $archive->close(); header('Content-type: application/octet-stream'); header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT'); header('Content-disposition: attachment; filename=' . Lang::createFilename($this->_Parent->Configuration->get('sitename', 'general')) . '-install.zip'); header('Pragma: no-cache'); readfile(TMP . '/install.tmp.zip'); unlink(TMP . '/install.tmp.zip'); exit; }
function db_dump() { global $db_server, $db_name, $db_user, $db_pass, $backup_filename, $html_output, $full_path; //$cmd = 'mysqldump -u ' . $db_user . ' -h ' . $db_server . ' --password='******' ' . ($db_name == '' ? '--all-databases' : $db_name) . ' | gzip > ' . $backup_filename; //$dump_status = (passthru($cmd) === false) ? 'No' : 'Yes'; $dumpSettings = array('compress' => CompressMethod::GZIP, 'no-data' => false, 'add-drop-table' => false, 'single-transaction' => true, 'lock-tables' => false, 'add-locks' => false, 'extended-insert' => true); $dump = new MySQLDump($db_name, $db_user, $db_pass, $db_server, $dumpSettings); $dump->start(str_replace('.gz', '', $backup_filename)); //echo 'Command: ' . $cmd . '<br />'; //echo 'Command executed? ' . $dump_status . '<br />'; return true; }
function syncMySQLData($link, $mdb_name, $live_db) { $dump = new MySQLDump(); $sql = $dump->dumpDatabase($mdb_name, $link); $sql = explode("\n", $sql); if (is_array($sql)) { foreach ($sql as $sqlstring) { $live_db->query($sqlstring); print "."; ob_flush(); flush(); } } return true; }
/** /** * Backup the current state of the Symphony database * This function can only be called from the Symphony backend, the CDI extension must be enabled and running in Database Synchronisation mode. * @param $mode The mode of backup: 'manual' or 'automatic'. This is used to determine which configuration setting should apply. */ public static function backup($mode) { // We should only backup the database when the extension is enabled and version 1.09 of the Dump_DB extension is installed. if((!class_exists('Administration')) || !CdiUtil::isEnabled()) { throw new Exception("You can only import the Database Synchroniser file from the Preferences page"); } if(!CdiUtil::hasDumpDBInstalled()) { throw new Exception('No valid version of <a href="http://symphony-cms.com/download/extensions/view/40986/">Dump DB</a> found. Please make sure it is installed.'); } else { require_once(EXTENSIONS . '/dump_db/lib/class.mysqldump.php'); // Prevent the CdiLogQuery::log() from persisting queries that are executed by CDI itself CdiLogQuery::isUpdating(true); // COPIED FROM Dump_DB version 1.09 // Adjust to only support FULL database dump $sql = CdiUtil::getMetaData(); $dump = new MySQLDump(Symphony::Database()); $rows = Symphony::Database()->fetch("SHOW TABLES LIKE 'tbl_%';"); $rows = array_map (create_function ('$x', 'return array_values ($x);'), $rows); $tables = array_map (create_function ('$x', 'return $x[0];'), $rows); // Get DATA from all tables foreach ($tables as $table){ $table = str_replace(Symphony::Configuration()->get('tbl_prefix', 'database'), 'tbl_', $table); $sql .= $dump->export($table, MySQLDump::ALL); $sql = str_replace(Symphony::Configuration()->get('tbl_prefix', 'database'), 'tbl_', $sql); } // Persist SQL data to file if(($mode == 'automatic' && Symphony::Configuration()->get('backup-overwrite', 'cdi') == 'yes') || ($mode == 'manual' && Symphony::Configuration()->get('manual-backup-overwrite', 'cdi') == 'yes')) { self::uninstall(); } $filename = self::getFileName($mode); file_put_contents($filename,$sql); // Re-enable CdiLogQuery::log() to persist queries CdiLogQuery::isUpdating(false); // Return the filename of the backup for automatic restore return $filename; } }
/** * @param string $fileNamePrefix * @param bool $removeBackupFileAtTheEnd * @throws \Exception * @throws IOException * @return ResultObject[] */ public function backup($fileNamePrefix = null, $removeBackupFileAtTheEnd = false) { $storagePath = $this->prepareStoragePath($this->backupTempPath); $file = new DatabaseBackupFile($storagePath); if (!empty($fileNamePrefix)) { $file->setNamePrefix($fileNamePrefix); } $this->mysqlDump->save($file->getFilePath()); $resultObjects = []; /** @var IDatabaseBackupHandler $handler */ foreach ($this->backupHandlers as $handler) { $results = $handler->process($file); $resultObjects = array_merge($resultObjects, $results); } if ($removeBackupFileAtTheEnd === true) { $this->removeBackupFile($file); } return Arrays::flatten($resultObjects); }
public function backupnupload() { // $cloud=new Cloud; $dump = new \MySQLDump(new \mysqli(config("database.connections.mysql.host"), config("database.connections.mysql.username"), config("database.connections.mysql.password"), config("database.connections.mysql.database"))); $dump->save('export.sql.gz'); $filename = "thinkmeritapi." . Carbon::now()->format('d-m-Y h.i.s A') . '.zip'; \Log::info('Generating backup file - ' . $filename); // Get real path for our folder $rootPath = realpath(base_path()); // Initialize archive object $zip = new \ZipArchive(); $zip->open('public/' . $filename, \ZipArchive::CREATE | \ZipArchive::OVERWRITE); // Create recursive directory iterator /** @var SplFileInfo[] $files */ $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($rootPath), \RecursiveIteratorIterator::LEAVES_ONLY); echo "Creating zip file."; foreach ($files as $name => $file) { // Skip directories (they would be added automatically) if (strpos($name, 'vendor') !== false || strpos($name, 'node_modules') !== false || strpos($name, 'cache') !== false) { continue; } else { if (!$file->isDir()) { // Get real and relative path for current file $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($rootPath) + 1); // Add current file to archive $zip->addFile($filePath, $relativePath); } } } // Zip archive will be created only after closing object $zip->close(); \Log::info('Completed making zip file - ' . $filename); echo "Uploading zip backup file."; \Log::info('Uploading backup zip - ' . $filename); $this->cloud->put($filename, file_get_contents('public/' . $filename)); \Log::info('Uploading success - ' . $filename); unlink('public/' . $filename); unlink('export.sql.gz'); return $filename . " backup file successfully generated."; }
/** * Writes to file the selected database dump * * @return bool */ function doFKDump($params = array()) { parent::doDump($params, false); $this->getForeignKeys(); $sql_file = "-- ------------\n"; $sql_file .= "-- FOREIGN KEYS\n"; $sql_file .= "-- ------------\n"; $sql_file .= "SET FOREIGN_KEY_CHECKS = 0;\n\n"; $sql_file .= $this->getForeignKeysRules(); $sql_file .= "SET FOREIGN_KEY_CHECKS = 1;\n\n"; $this->saveToFile($this->file, $sql_file); $this->closeFile($this->file); return true; }
public function backupAction() { $log = $this->getServiceLocator()->get('log'); $log->addInfo('备份数据' . "\t" . $this->getRequest()->getServer('REMOTE_ADDR') . "\t" . $this->getRequest()->getHeaders()->get('User-Agent')->getFieldValue()); $dbconf = $this->getServiceLocator()->get('config')['mysqli']; $dump = new \MySQLDump(new \mysqli($dbconf['host'], $dbconf['username'], $dbconf['password'], $dbconf['dbname'])); $filename = date("Y-m-d_H-i-s") . "-db.sql"; $tmpFile = dirname(__FILE__) . "\\" . $filename; $dump->save($tmpFile); $body = new Message(); $part = new Part(); $part->setType(Mime::TYPE_OCTETSTREAM); $part->setContent(file_get_contents($tmpFile)); $part->setDisposition(Mime::DISPOSITION_ATTACHMENT); $part->setFileName($filename); $part2 = new Part(); $part2->setType(Mime::TYPE_TEXT); $part2->setContent('小秋来发数据了'); $body->addPart($part); $body->addPart($part2); $newmessage = new \Zend\Mail\Message(); $newmessage->addTo($this->getServiceLocator()->get('MailOptions')->getMailTo()); $newmessage->addFrom($this->getServiceLocator()->get('MailOptions')->getMailFrom()); $newmessage->setBody($body); $newmessage->setSubject('备份数据'); $transport = new SmtpTransport(); $options = new SmtpOptions($this->getServiceLocator()->get('config')['mail']); $transport->setOptions($options); try { $transport->send($newmessage); echo 1; } catch (\Exception $e) { echo -1; } exit; }
function init() { parent::init(); preg_match('|([a-z]+)://([^:]*)(:(.*))?@([A-Za-z0-9\\.-]*)' . '(/([0-9a-zA-Z_/\\.-]*))|', $this->app->getConfig('dsn'), $matches); $form = $this->add('Form'); $form->addField('username'); $form->addField('password', 'password'); $form->addField('mysql_host')->set($matches[5]); $form->addField('mysql_user')->set($matches[2]); $form->addField('password', 'mysql_password')->set($matches[4]); $form->addField('mysql_db')->set($matches[7]); $form->onSubmit(function ($f) { if (!$this->app->auth->verifyCredentials($f['username'], $f['password'])) { $f->displayError('username', 'Sorry, you cant reset database'); } try { $user = clone $this->app->auth->model; $this->api->db->beginTransaction(); $this->app->db->dsql()->expr('SET FOREIGN_KEY_CHECKS = 0;')->execute(); $this->app->resetDB = true; foreach ($this->app->xepan_addons as $addon) { $this->app->xepan_app_initiators[$addon]->resetDB(); } $this->app->db->dsql()->expr('SET FOREIGN_KEY_CHECKS = 1;')->execute(); $this->api->db->commit(); } catch (\Exception_StopInit $e) { } catch (\Exception $e) { $this->api->db->rollback(); $this->app->auth->login($user); throw $e; } $dump = new \MySQLDump(new \mysqli($f['mysql_host'], $f['mysql_user'], $f['mysql_password'], $f['mysql_db'])); $dump->save(getcwd() . '/../install.sql'); return "SQL Generated"; }); }
static function dump_database($include_history = false) { global $page, $conf, $cfgBase; if (version_compare(PHPWG_VERSION, '2.1', '<')) { $conf['db_base'] = $cfgBase; } include PHPWG_ROOT_PATH . 'admin/include/mysqldump.php'; $path = PHPWG_ROOT_PATH . $conf['data_location'] . 'update'; if (@mkgetdir($path) and $backupFile = tempnam($path, 'sql') and $dumper = new MySQLDump($conf['db_base'], $backupFile, false, false)) { foreach (get_defined_constants() as $constant => $value) { if (preg_match('/_TABLE$/', $constant)) { $dumper->getTableStructure($value); if ($constant == 'HISTORY_TABLE' and !$include_history) { continue; } $dumper->getTableData($value); } } } if (@filesize($backupFile)) { $http_headers = array('Content-Length: ' . @filesize($backupFile), 'Content-Type: text/x-sql', 'Content-Disposition: attachment; filename="database.sql";', 'Content-Transfer-Encoding: binary'); foreach ($http_headers as $header) { header($header); } @readfile($backupFile); deltree(PHPWG_ROOT_PATH . $conf['data_location'] . 'update'); exit; } else { $page['errors'][] = l10n('Unable to dump database.'); } }
private function __export() { $sql_schema = $sql_data = NULL; require_once dirname(__FILE__) . '/lib/class.mysqldump.php'; $dump = new MySQLDump(Symphony::Database()); $tables = array('tbl_authors', 'tbl_cache', 'tbl_entries', 'tbl_extensions', 'tbl_extensions_delegates', 'tbl_fields', 'tbl_fields_%', 'tbl_forgotpass', 'tbl_pages', 'tbl_pages_types', 'tbl_sections', 'tbl_sections_association'); ## Grab the schema foreach ($tables as $t) { $sql_schema .= $dump->export($t, MySQLDump::STRUCTURE_ONLY); } $sql_schema = str_replace('`' . Symphony::Configuration()->get('tbl_prefix', 'database'), '`tbl_', $sql_schema); $sql_schema = preg_replace('/AUTO_INCREMENT=\\d+/i', NULL, $sql_schema); $tables = array('tbl_entries', 'tbl_extensions', 'tbl_extensions_delegates', 'tbl_fields', 'tbl_pages', 'tbl_pages_types', 'tbl_sections', 'tbl_sections_association'); ## Field data and entry data schemas needs to be apart of the workspace sql dump $sql_data = $dump->export('tbl_fields_%', MySQLDump::ALL); $sql_data .= $dump->export('tbl_entries_%', MySQLDump::ALL); ## Grab the data foreach ($tables as $t) { $sql_data .= $dump->export($t, MySQLDump::DATA_ONLY); } $sql_data = str_replace('`' . Symphony::Configuration()->get('tbl_prefix', 'database'), '`tbl_', $sql_data); $config_string = NULL; $config = Symphony::Configuration()->get(); unset($config['symphony']['build']); unset($config['symphony']['cookie_prefix']); unset($config['general']['useragent']); unset($config['file']['write_mode']); unset($config['directory']['write_mode']); unset($config['database']['host']); unset($config['database']['port']); unset($config['database']['user']); unset($config['database']['password']); unset($config['database']['db']); unset($config['database']['tbl_prefix']); unset($config['region']['timezone']); foreach ($config as $group => $set) { foreach ($set as $key => $val) { $config_string .= "\t\t\$conf['{$group}']['{$key}'] = '{$val}';" . self::CRLF; } } $install_template = str_replace(array('<!-- VERSION -->', '<!-- CONFIGURATION -->'), array(Symphony::Configuration()->get('version', 'symphony'), trim($config_string)), file_get_contents(dirname(__FILE__) . '/lib/installer.tpl')); $archive = new ZipArchive(); $res = $archive->open(TMP . '/ensemble.tmp.zip', ZipArchive::CREATE); if ($res === TRUE) { $this->__addFolderToArchive($archive, EXTENSIONS, DOCROOT); $this->__addFolderToArchive($archive, SYMPHONY, DOCROOT); $this->__addFolderToArchive($archive, WORKSPACE, DOCROOT); $archive->addFromString('install.php', $install_template); $archive->addFromString('install.sql', $sql_schema); $archive->addFromString('workspace/install.sql', $sql_data); $archive->addFile(DOCROOT . '/index.php', 'index.php'); $readme_files = glob(DOCROOT . '/README.*'); if (is_array($readme_files) && !empty($readme_files)) { foreach ($readme_files as $filename) { $archive->addFile($filename, basename($filename)); } } if (is_file(DOCROOT . '/README')) { $archive->addFile(DOCROOT . '/README', 'README'); } if (is_file(DOCROOT . '/LICENCE')) { $archive->addFile(DOCROOT . '/LICENCE', 'LICENCE'); } if (is_file(DOCROOT . '/update.php')) { $archive->addFile(DOCROOT . '/update.php', 'update.php'); } } $archive->close(); header('Content-type: application/octet-stream'); header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT'); header(sprintf('Content-disposition: attachment; filename=%s-ensemble.zip', Lang::createFilename(Symphony::Configuration()->get('sitename', 'general')))); header('Pragma: no-cache'); readfile(TMP . '/ensemble.tmp.zip'); unlink(TMP . '/ensemble.tmp.zip'); exit; }
} if ($mode & self::TRIGGERS) { $res = $this->connection->query("SHOW TRIGGERS LIKE '" . $this->connection->real_escape_string($table) . "'"); if ($res->num_rows) { fwrite($handle, "DELIMITER ;;\n\n"); while ($row = $res->fetch_assoc()) { fwrite($handle, "CREATE TRIGGER {$this->delimite($row['Trigger'])} {$row['Timing']} {$row['Event']} ON {$delTable} FOR EACH ROW\n{$row['Statement']};;\n\n"); } fwrite($handle, "DELIMITER ;\n\n"); } $res->close(); } fwrite($handle, "\n"); } private function delimite($s) { return '`' . str_replace('`', '``', $s) . '`'; } } $db_host = '$DB_HOST'; $db_port = '$DB_PORT'; if (!$db_port) { $db_port = ini_get("mysqli.default_port"); } $db_user = '******'; $db_password = '******'; $db_name = '$DB_NAME'; $sql_dir = '$SQL_DIR'; $connection = new mysqli($db_host, $db_user, $db_password, $db_name, $db_port); $dump = new MySQLDump($connection); $dump->save($sql_dir . 'dump.sql');
/** * @param $filePath * @throws Exception */ public function save($filePath) { $this->mysqlDump->save($filePath); }
private function __dump($context) { $sql_schema = $sql_data = NULL; require_once dirname(__FILE__) . '/lib/class.mysqldump.php'; $dump = new MySQLDump(Symphony::Database()); $rows = Symphony::Database()->fetch("SHOW TABLES LIKE 'tbl_%';"); $rows = array_map(create_function('$x', 'return array_values ($x);'), $rows); $tables = array_map(create_function('$x', 'return $x[0];'), $rows); $mode = NULL; $mode = isset($_POST['action']['dump']['authors']) ? 'authors' : 'data'; if ($mode == NULL) { return; } $filename = $this->generateFilename($mode); foreach ($tables as $table) { $table = str_replace(Symphony::Configuration()->get('tbl_prefix', 'database'), 'tbl_', $table); if ($mode == 'authors') { switch ($table) { case 'tbl_authors': case 'tbl_forgotpass': $sql_data .= $dump->export($table, MySQLDump::ALL); break; case 'tbl_sessions': $sql_data .= $dump->export($table, MySQLDump::STRUCTURE_ONLY); break; default: // ignore everything but the authors break; } } elseif ($mode == 'data') { switch ($table) { case 'tbl_authors': // ignore authors // ignore authors case 'tbl_forgotpass': case 'tbl_sessions': break; case 'tbl_cache': case 'tbl_search_index': case 'tbl_search_index_entry_keywords': case 'tbl_search_index_keywords': case 'tbl_search_index_logs': $sql_data .= $dump->export($table, MySQLDump::STRUCTURE_ONLY); break; default: $sql_data .= $dump->export($table, MySQLDump::ALL); } } } if (Symphony::Configuration()->get('dump', 'dump_db') === 'download') { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/octet-stream"); header("Content-Transfer-Encoding: binary"); header("Content-Disposition: attachment; filename=" . $mode . ".sql"); echo $sql_data; die; } elseif (Symphony::Configuration()->get('dump', 'dump_db') === 'text') { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: text/plain; charset=UTF-8"); echo $sql_data; die; } else { if (FALSE !== @file_put_contents(DOCROOT . $this->path . '/' . $filename, $sql_data)) { Administration::instance()->Page->pageAlert(__('%s successfully dumped into <code>%s/%s</code>.', array(__(ucfirst($mode)), $this->path, $filename)), Alert::SUCCESS); Symphony::Configuration()->set('last_sync', date('c'), 'dump_db'); Symphony::Configuration()->write(); } else { Administration::instance()->Page->pageAlert(__('An error occurred while trying to write <code>%s/%s</code>.', array($this->path, $filename)), Alert::ERROR); } } }
require_once 'MySQLDump.class.php'; $starttime = time(); //mysql info $dbhost = $db_HOST; //db host $dbuser = $db_USER; //db user name $dbpass = $db_PASS; //db password $dbname = $db_NAME; //db to work with $drop_table_if_exists = true; //should we drop table if exist? $somecontent = "/*\n\n+-------------------------------------------------------------+\n\n+-------------------------------------------------------------+\n\n+---------By:Amila Jayasinghe (amilaplus@gmail.com)-----------+\n\n+-------------------------------------------------------------+\n\n*/\n\n"; // no need for editing further $backup = new MySQLDump(); //create new instance of MySQLDump $backup->droptableifexists = $drop_table_if_exists; //set drop table if exists $backup->connect($dbhost, $dbuser, $dbpass, $dbname); //connect if (!$backup->connected) { die('Error: ' . $backup->mysql_error); } //if not connected, display error $backup->list_tables(); //list all tables $broj = count($backup->tables); //count all tables, $backup->tables will be array of table names //echo "<pre>\n"; //start preformatted output $somecontent .= "-- Dumping tables for database: `{$dbname}`\n";
<?php set_time_limit(0); ignore_user_abort(TRUE); require __DIR__ . '/../src/MySQLDump.php'; $dump = new MySQLDump(new mysqli('localhost', 'root', 'password', 'database')); ini_set('zlib.output_compression', TRUE); header('Content-Type: application/x-gzip'); header('Content-Disposition: attachment; filename="dump ' . date('Y-m-d H-i') . '.sql.gz"'); header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT'); header('Cache-Control: no-cache'); header('Connection: close'); $dump->write();
for ($x = 0; $x < $num_fields; $x++) { $field_name = mysql_field_name($result, $x); $data .= "'" . str_replace('\\"', '"', mysql_escape_string($row->{$field_name})) . "'"; $data .= $x < $num_fields - 1 ? ", " : false; } $data .= ");\n"; } $data .= "\n"; $dump .= $structure . $data; $dump .= "-- --------------------------------------------------------\n\n"; } return $dump; } } } $dump = new MySQLDump(); ob_start("ob_gzhandler"); error_reporting(0); $s = $dump->dumpDatabase(MYSQL_DB); print $s; } function objects_list($table, $fields, $where, $order, $action_string) { if ($where) { $where .= " WHERE {$where} "; } if ($order) { $order .= " ORDER BY {$order} "; } $res = db_query("SELECT id, {$fields} FROM {$table} {$where} {$order}"); return htmlquery_code($res, $action_string);
<?php set_time_limit(0); ignore_user_abort(TRUE); require __DIR__ . '/../src/MySQLDump.php'; $time = -microtime(TRUE); $dump = new MySQLDump(new mysqli('localhost', 'root', 'password', 'database')); $dump->save('dump ' . date('Y-m-d H-i') . '.sql.gz'); $time += microtime(TRUE); echo "FINISHED (in {$time} s)";
/** * * @param \KEvent $event */ public function onAfterSchemaMigration(\KEvent $event) { if ($event->caller->getComponent() == 'anahita') { $path = ANAHITA_ROOT . '/vendor/joomla/installation/sql'; $event->caller->setOutputPath($path); } $tables = $event->caller->getTables(); $schema_file = $event->caller->getOutputPath() . '/schema.sql'; $uninstall_file = $event->caller->getOutputPath() . '/uninstall.sql'; $schema = fopen($schema_file, 'w'); $uninstall = fopen($uninstall_file, 'w'); $dump = new \MySQLDump($event->caller->getDatabaseAdapter()->getConnection()); $prefix_replace = array(); foreach ($tables as $table) { $prefix_replace[$table] = str_replace($event->caller->getDatabaseAdapter()->getTablePrefix(), '#__', $table); $dump->tables[$table] = \MySQLDump::CREATE; $dump->dumpTable($schema, $table); $dump->tables[$table] = \MySQLDump::DROP; $dump->dumpTable($uninstall, $table); } $version = $event->caller->getCurrentVersion(); $component = $event->caller->getComponent(); fwrite($schema, "INSERT INTO #__migrator_versions (`version`,`component`) " . "VALUES({$version}, '{$component}') ON DUPLICATE KEY UPDATE `version` = {$version};"); fwrite($uninstall, "DELETE #__migrator_versions WHERE `component` = '{$component}';"); fclose($schema); fclose($uninstall); //fix the prefix foreach (array($schema_file, $uninstall_file) as $file) { $content = file_get_contents($file); $content = str_replace(array_keys($prefix_replace), array_values($prefix_replace), $content); file_put_contents($file, $content); } $content = file_get_contents($schema_file); $replace = array('/ TYPE=/' => ' ENGINE=', '/ AUTO_INCREMENT=\\w+/' => ''); //fix the auto increment $content = preg_replace(array_keys($replace), array_values($replace), file_get_contents($schema_file)); file_put_contents($schema_file, $content); //delete uninsall file for anahita if ($event->caller->getComponent() == 'anahita') { unlink($uninstall_file); } }
private function mysqlDump($dumpname) { require_once root . "/resource/phpmysqldumper/MySQLDump.php"; $dumper = new \MySQLDump(new \mysqli(property::getInstance()->get('db_host'), property::getInstance()->get('db_user'), property::getInstance()->get('db_pass'), property::getInstance()->get('db_name'))); $dumper->save(root . $dumpname); }
* @licence https://github.com/symphonycms/symphony-1.7/blob/master/LICENCE * ***/ if (array_key_exists("begin", $_POST['action'])) { $start = time(); $Admin->log->writeToLog("============================================\r\n", true); $Admin->log->pushToLog("Beginning 1.1.00 Migration", SYM_LOG_NOTICE, true, true); ##Create Backup $Admin->log->pushToLog("Backing Up Existing Database...", SYM_LOG_NOTICE, true, false); require_once TOOLKIT . "/class.mysqldump.php"; $data = "\nTRUNCATE `tbl_entries`;"; $data .= "\nTRUNCATE `tbl_entries2customfields`;"; $data .= "\nTRUNCATE `tbl_comments`;"; $data .= "\nTRUNCATE `tbl_entries_types`;"; $data .= "\nDELETE FROM `tbl_metadata` WHERE `class` IN('entry', 'comment');"; $dump = new MySQLDump($DB); $data .= $dump->takeDump($Admin->getConfigVar("tbl_prefix", "database") . "entries", "DATA_ONLY"); $data .= $dump->takeDump($Admin->getConfigVar("tbl_prefix", "database") . "comments", "DATA_ONLY"); $data .= $dump->takeDump($Admin->getConfigVar("tbl_prefix", "database") . "metadata", "DATA_ONLY", "`class` IN('entry','comment')"); unset($dump); if (!@file_put_contents(TMP . "/migration-backup.sql", $data)) { define("__SYM_MIGRATION_ERRORS__", true); $Admin->log->pushToLog("Failed.", SYM_LOG_NOTICE, true, true, true); } else { $Admin->log->pushToLog("Done.", SYM_LOG_NOTICE, true, true, true); } ##Entries if (!defined("__SYM_MIGRATION_ERRORS__")) { $Admin->log->pushToLog("Migrating Entries Table", SYM_LOG_NOTICE, true, true); //--------------------- $TFM = new TextformatterManager(array('parent' => &$Admin));
# также есть вероятность, что файлы с кириллическими именами могут прерывать архивирование, но это не точные сведения # а вот точные сведения в том, что при архивировании также подхватываются предыдущие бекапы и общий вес увеличивается как снежный ком set_time_limit(0); /*** Дамп базы данных: ***/ include("../core/config/config.inc.php"); //include("class_mysqldump.php"); include("mysqldump.php"); $ready = false; if(count($_POST) && !empty($_POST["filename"])) { mysql_connect($database_server, $database_user, $database_password) or die("F*****g shit! We have troubles!"); $dumpFileName = "dumps/".$_POST["filename"].".sql"; $dumper = new MySQLDump($dbase,$dumpFileName,false,false); mysql_query("set names utf8"); @$dumper->doDump(); // фикс заменяющий неработающую CURRENT_TIMESTAMP на наших серверах $fileContents = file_get_contents($dumpFileName); $fileContents = str_ireplace('CURRENT_TIMESTAMP','0000-00-00 00:00:00',$fileContents); file_put_contents($dumpFileName , $fileContents); $ready = true; } $filename = "dump_".date("d-m-Y"); include("dumperview.php"); /*** /дамп базы данных ***/ /*** Архив сайта: ***/
} } //************* SESSION active past here ************************** //check permission levels $permission_level = getPermissionLevel($_SESSION['egps_username']); if ($permission_level > $MINIMUM_AUTHORIZATION_LEVEL || $permission_level == NULL) { $system_message = $system_message . "You do not have permission to view this page (IP: " . $_SERVER['REMOTE_ADDR'] . ")"; IPP_LOG($system_message, $_SESSION['egps_username'], 'ERROR'); require IPP_PATH . 'security_error.php'; exit; } //************** validated past here SESSION ACTIVE WRITE PERMISSION CONFIRMED**************** //include class require_once IPP_PATH . 'include/MySQLDump.class.php'; //create new instance of MySQLDump $backup = new MySQLDump(); //set drop table if exists $backup->droptableifexists = true; //connect to mysql server (host, user, pass, db) $backup->connect($mysql_data_host, $mysql_data_username, $mysql_data_password, 'ipp'); //if not connected, display error if (!$backup->connected) { die('Error: ' . $backup->mysql_error); } //get all tables in db $backup->list_tables(); //reset buffer $buffer = ''; //go through all tables and dump them to buffer foreach ($backup->tables as $table) { $buffer .= $backup->dump_table($table);
function rebuildWorkspaceConfig() { require_once TOOLKIT . "/class.mysqldump.php"; $dump = new MySQLDump($this->_db); $prefix = $this->getConfigVar("tbl_prefix", "database"); $data = $dump->takeDump($prefix . "pages", "DATA_ONLY"); $data .= $dump->takeDump($prefix . "customfields", "DATA_ONLY"); $meta = $dump->takeDump($prefix . "metadata", "DATA_ONLY", "`class` IN('page','customfield', 'section', 'master', 'utility')"); $data .= $dump->takeDump($prefix . "utilities", "DATA_ONLY"); $data .= $dump->takeDump($prefix . "masters", "DATA_ONLY"); $data .= $dump->takeDump($prefix . "sections", "DATA_ONLY"); unset($dump); ## Make sure the prefix is correct. We need it as 'tbl_' not the user specified one str_replace("`{$prefix}", '`tbl_', $data); ## Make sure we dont get metadata primary key collisions $meta = preg_replace('/VALUES \\(\\d+/i', "VALUES (''", $meta); $data .= $meta; @file_put_contents(WORKSPACE . "/workspace.conf", $data); if ($hash = @md5_file(WORKSPACE . "/workspace.conf")) { $this->setConfigVar("config_checksum", $hash, "workspace"); $this->saveConfig(); $this->flush_cache("ALL"); return true; } $this->log->pushToLog("ERROR: Rebuilding of workspace configuration failed", SYM_LOG_ERROR, true, true); return false; }
<?php /** * نسخ احتياطي لقاعدة البيانات * User: pc-sales * Date: 2/6/2016 * Time: 4:09 م */ require 'Class/MySQLDump.php'; require 'config.php'; set_time_limit(0); $time = microtime(TRUE); ignore_user_abort(TRUE); $dump = new MySQLDump(new mysqli($dataInfoArray['host'] . ":{$dataInfoArray['port']}", $dataInfoArray['username'], $dataInfoArray['password'], $dataInfoArray['db'])); $dump->save('C:/Users/win/OneDrive/AFix/AFix[' . date('Y-m-d--H-i-s') . '].sql.gz'); echo "تم اخذ نسخة احتياطية بنجاح ";