PHP Script Import Mysql Dump Gzip .sql.gz

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']) &amp;&amp; $_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, &amp;$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 != "." &amp;&amp; $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 &amp;$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>";
?>

Cicciokr

"Javascript is to Java as hamburger is to ham; both are delicious, but they don't have much in common except a name" I'm javascript lovers and this is my site on witch sometimes write about my experience, when i have some free time, and remember: "Homo faber fortunae suae"

Write a Comment

Your email address will not be published.