Skip to content

Instantly share code, notes, and snippets.

@duhow
Last active July 3, 2018 12:43
Show Gist options
  • Save duhow/d0a34126b1734ed0cb7c3149f55274ea to your computer and use it in GitHub Desktop.
Save duhow/d0a34126b1734ed0cb7c3149f55274ea to your computer and use it in GitHub Desktop.
PHP Table backup script
#!/usr/bin/php
<?php
$config = [
'host' => 'localhost',
'user' => 'root',
'pass' => '',
'db' => 'prestashop',
'prefix' => 'ps_',
'tables' => [
'address',
'customer(.+|$)',
'cart(.+|$)',
'message',
'orders',
'order(.+)',
'paypal(.+)',
'product',
'product_lang',
'specific_price'
],
'name' => 'backup_%y%m%d_%H%i%s_%T.sql',
'path' => getcwd() .'/',
'gzip' => TRUE
];
$db = new mysqli($config['host'], $config['user'], $config['pass'], $config['db']);
if($db->connect_errno){
error_log("ERROR connecting to DB: " .$db->connect_errno);
exit(1);
}
$tables = $db->query("SHOW TABLES");
if($tables->num_rows == 0){
error_log("No tables found.");
exit(1);
}
$backup_tables = array();
$match = '/^' .$config['prefix'] .'(' .implode('|', $config['tables']) .')' .'$/';
while($table = $tables->fetch_row()){
$table = current($table);
if(preg_match($match, $table)){
$backup_tables[] = $table;
}
}
if(count($backup_tables) == 0){
echo("No tables found in pattern, not doing backup.");
exit(0);
}
echo "Preparing backup for " .count($backup_tables) ." tables...\n";
$date_now = time();
foreach($backup_tables as $table){
$file = $config['name'];
$date_matches = "dDjlNSwzWFmMntLoYyaABgGhHisuveIOPZcr";
foreach(str_split($date_matches) as $m){
$file = str_replace('%' .$m, date("$m", $date_now), $file);
}
$file = str_replace("%T", $table, $file);
echo "> " .$file ."\n";
$time = microtime(TRUE);
$cmd = "mysqldump"
." --host=" .$config['host']
." --user=" .$config['user']
." --password=" .$config['pass']
." " .$config['db']
." " .$table;
exec($cmd ." > " .$config['path'] .$file);
$time = floor((microtime(TRUE) - $time) * 1000);
echo "Done in $time ms.";
if($config['gzip']){
echo " Compressing... ";
$time = microtime(TRUE);
exec("gzip " .$config['path'] .$file);
$time = floor((microtime(TRUE) - $time) * 1000);
echo "Done in $time ms.";
}
echo "\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment