Restore Mysql Database from a sql or zip file using PHP

In a previous post we learnt how to backup a mysql database and zip it inside php. In this example the same zip file would be used to restore the database.

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';
  }
}   






Last Updated On : 1st May 2009

Subscribe to get updates delivered to your inbox

About Silver Moon

Php developer, blogger and Linux enthusiast. He can be reached at [email protected]. Or find him on

2 Comments + Add Comment

  • Great site. The link to: ” the 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.”

    Is broken, hope to see it soon. Thanks

    • Thanks for pointing that out. Its fixed now.

Leave a comment