In many case we have the necessity to import a mysql dump in fast way on our database, to see some old data or to restore.

Now i want to show you a simple but powerful php script to import a mysql dump gzipped.

We use the function zcat with shell_exec

shell_exec("zcat <url file> | mysql -u <user_db> -p<password db> <database>")

This is a simple php script that we can use on our application, to restore in fast way our gzipped mysql dump

We create a select, to show a list of file, and then choose one and click “load”, then with our zcat shell execution function, load it.

<?php
if(isset($_POST['action']) && $_POST['action'] == 'execute')
{  
  $file_name = $_POST['filename'];
  $out = shell_exec("zcat ".$file_name." | mysql -u user_db -pPasswordDB db_name");
  echo "Mysql Dump Imported Successfull!";
}


function getDirContents($dir, &$results = array()){
    $files = scandir($dir);
    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            $results[] = $path;
        } else if($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = $path;
        }
    }

    return $results;
}

//directory of our backup file
$listFile = getDirContents('/var/www/vhosts/<our domain>/backups');
echo "<form method=POST>";
echo "<select name='filename'>";
foreach ($listFile as &$value) {
  echo "<option>".$value."</option>";
}
echo "</select>";
echo "<input type='hidden' name='action' value='execute'>";
echo "<input type='submit' name='Load Mysql Dump'>";
echo "</form>";
?>
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *