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

Last Updated On : 1st May 2009

Related Post

2 thoughts on “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 *