Restore Mysql Database from a sql or zip file using PHP

By | May 1, 2009

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.


// Function to restore from a file
function restore($path) {
  $f = fopen('restore/temp.sql' , 'w+');
  if(!$f) {
   echo "Error While Restoring Database";
  $zip = new ZipArchive();
  if ($zip->open($path) === TRUE) {
   #Get the backup content
   $sql = $zip->getFromName('backup.sql');
   #Close the Zip File
   #Prepare the sql file
   fwrite($f , $sql);
   #Now restore from the .sql file
   $command = "mysql --user={$username} --password={$password} --database={$db} < restore/temp.sql";
   #Delete temporary files without any warning
  else {
   echo 'Failed';
About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].


Restore Mysql Database from a sql or zip file using PHP
  1. Fred

    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

Leave a Reply

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