: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated in
* Define database parameters here
$upload_dir = wp_upload_dir();
$backup_dirname = $upload_dir['basedir'].'/wp-file-manager-pro/fm_backup';
define("BACKUP_DIR", $backup_dirname); // Comment this line to use same script's directory ('.')
define("TABLES", '*'); // Full backup
define("CHARSET", 'utf8');
define("GZIP_BACKUP_FILE", true); // Set to false if you want plain SQL backup files (not gzipped)
define("DISABLE_FOREIGN_KEY_CHECKS", true); // Set to true if you are having foreign key constraint fails
define("BATCH_SIZE", 1000); // Batch size when selecting rows from database in order to not exhaust system memory
// Also number of rows per INSERT statement in backup file
* The Backup_Database class
* Host where the database is located
* Username used to connect to database
* Password used to connect to database
* Backup directory where backup files are stored
* Use gzip compression on backup file
* Content of standard output
* Disable foreign key checks
var $disableForeignKeyChecks;
* Batch size, number of rows to process per iteration
* Constructor initializes database
public function __construct($filename) {
$this->username = DB_USER;
$this->passwd = DB_PASSWORD;
$this->charset = DB_CHARSET;
$this->conn = $this->initializeDatabase();
$this->backupDir = BACKUP_DIR ? BACKUP_DIR : '.';
$this->backupFile = $filename.'-db.sql';
$this->gzipBackupFile = defined('GZIP_BACKUP_FILE') ? GZIP_BACKUP_FILE : true;
$this->disableForeignKeyChecks = defined('DISABLE_FOREIGN_KEY_CHECKS') ? DISABLE_FOREIGN_KEY_CHECKS : true;
$this->batchSize = defined('BATCH_SIZE') ? BATCH_SIZE : 1000; // default 1000 rows
protected function initializeDatabase() {
$conn = mysqli_connect($this->host, $this->username, $this->passwd, $this->dbName);
if (mysqli_connect_errno()) {
throw new Exception('ERROR connecting database: ' . mysqli_connect_error());
if (!mysqli_set_charset($conn, $this->charset)) {
mysqli_query($conn, 'SET NAMES '.$this->charset);
print_r($e->getMessage());
* Backup the whole database or just some tables
* Use '*' for whole database or 'table1 table2 table3...'
public function backupTables($tables = '*', $bkpDir="") {
$result = mysqli_query($this->conn, 'SHOW TABLES');
while($row = mysqli_fetch_row($result)) {
$tables = is_array($tables) ? $tables : explode(',', str_replace(' ', '', $tables));
$sql = 'CREATE DATABASE IF NOT EXISTS `'.$this->dbName."`;\n\n";
$sql .= 'USE `'.$this->dbName."`;\n\n";
* Disable foreign key checks
if ($this->disableForeignKeyChecks === true) {
$sql .= "SET foreign_key_checks = 0;\n\n";
foreach($tables as $table) {
$this->obfPrint("Backing up `".$table."` table...".str_repeat('.', 50-strlen($table)), 0, 0);
$sql .= 'DROP TABLE IF EXISTS `'.$table.'`;';
$row = mysqli_fetch_row(mysqli_query($this->conn, 'SHOW CREATE TABLE `'.$table.'`'));
$sql .= "\n\n".$row[1].";\n\n";
$row = mysqli_fetch_row(mysqli_query($this->conn, 'SELECT COUNT(*) FROM `'.$table.'`'));
// Split table in batches in order to not exhaust system memory
$numBatches = intval($numRows / $this->batchSize) + 1; // Number of while-loop calls to perform
for ($b = 1; $b <= $numBatches; $b++) {
$query = 'SELECT * FROM `' . $table . '` LIMIT ' . ($b * $this->batchSize - $this->batchSize) . ',' . $this->batchSize;
$result = mysqli_query($this->conn, $query);
$realBatchSize = mysqli_num_rows ($result); // Last batch size can be different from $this->batchSize
$numFields = mysqli_num_fields($result);
if ($realBatchSize !== 0) {
$sql .= 'INSERT INTO `'.$table.'` VALUES ';
for ($i = 0; $i < $numFields; $i++) {
while($row = mysqli_fetch_row($result)) {
for($j=0; $j<$numFields; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
$row[$j] = str_replace("\r","\\r",$row[$j]);
$row[$j] = str_replace("\f","\\f",$row[$j]);
$row[$j] = str_replace("\t","\\t",$row[$j]);
$row[$j] = str_replace("\v","\\v",$row[$j]);
$row[$j] = str_replace("\a","\\a",$row[$j]);
$row[$j] = str_replace("\b","\\b",$row[$j]);
if (preg_match('/^-?[0-9]+$/', $row[$j]) or $row[$j] == 'NULL' or $row[$j] == 'null') {
$sql .= '"'.$row[$j].'"' ;
if ($j < ($numFields-1)) {
if ($rowCount == $realBatchSize) {
$sql.= ");\n"; //close the insert statement
$sql.= "),\n"; //close the row
* Re-enable foreign key checks
if ($this->disableForeignKeyChecks === true) {
$sql .= "SET foreign_key_checks = 1;\n";
if ($this->gzipBackupFile) {
$this->obfPrint('Backup file succesfully saved to ' . $this->backupDir.'/'.$this->backupFile, 1, 1);
print_r($e->getMessage());
protected function saveFile(&$sql) {
if (!file_exists($this->backupDir)) {
mkdir($this->backupDir, 0777, true);
file_put_contents($this->backupDir.'/'.$this->backupFile, $sql, FILE_APPEND | LOCK_EX);
print_r($e->getMessage());
* @param integer $level GZIP compression level (default: 9)
* @return string New filename (with .gz appended) if success, or false if operation fails
protected function gzipBackupFile($level = 9) {
if (!$this->gzipBackupFile) {
$source = $this->backupDir . '/' . $this->backupFile;
$this->obfPrint('Gzipping backup file to ' . $dest . '... ', 1, 0);
if ($fpOut = gzopen($dest, $mode)) {
if ($fpIn = fopen($source,'rb')) {
gzwrite($fpOut, fread($fpIn, 1024 * 256));
* Prints message forcing output buffer flush
public function obfPrint ($msg = '', $lineBreaksBefore = 0, $lineBreaksAfter = 1) {
if ($msg != 'OK' and $msg != 'KO') {
$msg = date("Y-m-d H:i:s") . ' - ' . $msg;
if (php_sapi_name() != "cli") {
if ($lineBreaksBefore > 0) {
for ($i = 1; $i <= $lineBreaksBefore; $i++) {
if ($lineBreaksAfter > 0) {
for ($i = 1; $i <= $lineBreaksAfter; $i++) {
// Save output for later use
$this->output .= str_replace('<br />', '\n', $output);
if (php_sapi_name() != "cli") {
if( ob_get_level() > 0 ) {
* Returns full execution output
public function getOutput() {