Restore Mysql Database from a sql or zip file using PHP

In the previous post we saw how the backup of a database can be taken in the form of a sql file and then zipped.

In this example the same zip file would be used to restore the database from it.

Code :

#Function to restore from a file
function restore($path) {
  $f = fopen('restore/temp.sql' , 'w+');
  if(!$f) {
   echo "Error While Restoring Database";
   return;
  }
  $zip = new ZipArchive();
  if ($zip->open($path) === TRUE) {
   #Get the backup content
   $sql = $zip->getFromName('backup.sql');
   #Close the Zip File
   $zip->close();
   #Prepare the sql file
   fwrite($f , $sql);
   fclose($f);

   #Now restore from the .sql file
   $command = "mysql --user={$username} --password={$password} --database={$db} < restore/temp.sql";
   exec($command);

   #Delete temporary files without any warning
   @unlink('restore/temp.sql');
  }
  else {
   echo 'Failed';
  }
}   

Popularity: 3% [?]

Leave a Reply