How to create a zip file using PHP and MySQL?

 

Today I came up with a new tutorial. In this article you are going to learn how to create a zip file using PHP and download it in zip format. Here I am using MySQL database as well, because you will get an idea that how to export images in zip format which is stored in a database.For your convenience let’s take an example, suppose you have a user table and there is another table named user_image_gallery table which stores all the gallery images of user. You can download all the user gallery images at once rather than one by one. Lets see step by step how to do it in PHP.

Database
Below is the table structure of user and user_image_gallery table.

user Table

CREATE TABLE IF NOT EXISTS user (
  uid int(11) NOT NULL AUTO_INCREMENT,
  uname varchar(50) NOT NULL,
  PRIMARY KEY (uid)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

user_image_gallery Table

CREATE TABLE IF NOT EXISTS user_image_gallery (
  gm_id int(11) NOT NULL AUTO_INCREMENT,
  uid int(11) NOT NULL,
  img_name varchar(30) NOT NULL,
  PRIMARY KEY (gm_id),
  KEY uid (uid)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

We have 2 tables user table which stores the user information and another table name is user_image_gallery which stores all the gallery image of the user and uid column which is the reference key with user table.

config.php
This is the database configuration file

<?php
define("DB_HOSTNAME","localhost");
define("DB_USERNAME","root");
define("DB_PASSWORD","");
define("DB_NAME","test");
$con = mysqli_connect(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD,DB_NAME);

// If connection failed then display error and exit
if (mysqli_connect_errno())
  {
  	 die(mysqli_connect_error());
  }
?>

Upload Folder:
Create a folder inside your project and name it “upload”, where all uploaded images will store in this folder.In this script I have created the folder under “c:/xampp/htdocs/my_project/upload”

index.php

<?php
include("config.php");
if($_SERVER['REQUEST_METHOD']=='POST'){
	if (extension_loaded('zip')) {
		$sql="SELECT img_name FROM user_image_gallery ORDER BY img_name ASC";
		$result=mysqli_query($con,$sql);
		if(mysqli_num_rows($result)>0){			
			$file_path=$_SERVER["DOCUMENT_ROOT"]."/my_project/upload/";//This should be absolute path of the upload folder where all the images are stored
			$zip = new ZipArchive(); //Call the ZIP constructor
			$zip_file_name=time().".zip"; //create zip filename with current datetime
			if($zip->open($zip_file_name,ZipArchive::CREATE)===true){				
				while($row=mysqli_fetch_array($result)){
					if(file_exists($file_path.$row["img_name"])){
						$zip->addFile($file_path.stripslashes($row["img_name"]),stripslashes($row["img_name"]));						
					}
				}					
			}else{
				die("There is some error while creating the zip file.");
			}
			
			$zip->close();//close
			if(file_exists($zip_file_name)){			
				//download the zip file
				header('Content-type: application/zip');
				header('Content-Disposition: attachment; filename="'.$zip_file_name.'"');
				readfile($zip_file_name);
				//After download the zip file which is created deleted it
				unlink($zip_file_name);
			}

		}
	}else{
		die("Zip extension is not loaded.");	
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>How to create a ZIP file in PHP</title>
</head>
<body>
<form action="" method="post">
  <table width="100%" border="0">
    <tr>
      <td align="center"><input type="submit" value="Download" /></td>
    </tr>
  </table>
</form>
</body>
</html>

In the above code there is a simple form along with a submit button.Once user clicks on the submit button the PHP code block executes.The PHP function extension_loaded is used to check whether zip library extension is loaded or not.Next the sql query retrieves all images name from the user_image_gallery table.Then the $file_path variable store the absolute path of the image folder.(Always mention the absolute path).Then next call the ZipArchive constructor.Then $zip_file_name variable is used which will creating the zip filename when download, in this case current time is used.You can give it any name like example.zip.

Next open method is used which open a new zip archive file for reading, writing or modifying.It accepts upto 2 parameters.First parameter is the zip file name whereas second parameter is the mode which is used to open the zip archieve.The second paramter value should be (ZipArchive::OVERWRITE,ZipArchive::CREATE,ZipArchive::EXCL or ZipArchive::CHECKCONS).

Next addFile zip archieve function is used.This function adds file to the ZIP archieve from given path.It accepts upto 4 parameters where first parameter is required. The first parameter should be absolute path of the file which you want to add in the zip archieve. If second parameter is not used then this function adds the full file path to the zip archieve. If you have passed the file name in the second parameter then this function adds “your-project/upload/image1.jpg” as “image1.jpg”.Third and fourth parameters are not mandatory.

After adding all files close function close the active archive file.

In the next section file_exists is used which checks whether the zip archieve file exists or not, if it exists then the header function read the zip file and download as an attachment.Finally when you download the file as attachment it creates the zip file under your project path so unlink function is used which deletes the file from the given path and free up some space.

If you have any query then feel free to contact me here

COMMENTS ( 3 )

DougFReges says:

I enjoy, cause I found exactly what I was looking for.
You’ve ended my 4 day long hunt! God Bless you man. Have a nice day.
Bye

Reply

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories