Create Zip files and Download Zip file in PHP Code

Zip file downloading is used by websites. The most important and popular of theme is WordPress. They use Zip files for downloading plugins, themes and even their versions. They do it off course, dynamically. You just provide the location of the file and PHP will download it to the user for you. Actually HTTP headers have the main role in the downloading.

We make the headers using header function in PHP and the browser will take care of the rest. The file path that you provide must be the absolute path. These are the two variables where you provide information about the Zip file :

See also

How to Create Zip Files using PHP ZipArchive and Download

Creating a ZIP file from a folder full of files can be done in PHP using the ZipArchive class. This instance of the class creates a handle to read or write files in the compressed archive.

In this article we will learn

  • How to create a zip archive file from database
  • How to download the compressed zip file dynamically

How to create a zip archive file

This file parses the input directory and compresses its files into a ZIP file. Follow the steps below to create a directory zip file.

  • Create a PHP ZipArchive class instance.
  • Open a zip file archive with the instance. It accepts the output zip file name and the mode to open the archive.
  • Apply a recursive parsing in the input directory.
  • If the directory includes a file, then it adds to the zip archive using addFile().

It handles the use cases of getting the possibilities of being unable to read or archive the directory. Once the zip is created, it displays a message to the browser.

If you want to know How to Force Download file in PHP refer to this earlier article.

Error Installing extension “Class ZipArchive” not found

The error “Class “ZipArchive” not found” indicates that the ZipArchive class is missing in your php installation, which is required to import the theme.
To fix this issue, you need to install the “php-zip” module on your server. The easiest way to do this is to contact your hosting provider and ask them to install it for you. If you have access to your server’s command line, you can also install it yourself. Here’s how:

  1. For Linux:
  • Log in to your server as root user.
  • Use the following command to install the “php-zip” module:
  • sudo apt-get install php-zip
  • Restart your Apache or Nginx server.
  1. For Windows:
  • Log in to your server as an administrator.
  • Go to the PHP directory (e.g. C:\php).
  • Find the “php.ini” file and open it in a text editor.
  • Add the following line to the end of the file: extension=zip.dll
  • Save and close the file.
  • Restart the Apache or IIS server.

Once you’ve installed the “php-zip” module, you should be able to import your theme into php without encountering the “Class “ZipArchive” not found” error.

Folder Structure

Create Zip files and Download Zip file in PHP Code

Create Database and Table by SQL query

Web need to create database and table, so here I create webscodex database and table. products table holds the records which will be save in products table and create zip file download from database using php. You can simply create table as following SQL query.

-- Database: `webscodex`
--
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `product_name` varchar(100) NOT NULL,
  `image` varchar(100) NOT NULL,
  `description` text NOT NULL,
  `price` int(50) NOT NULL,
  `status` tinyint(4) NOT NULL,
  `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

Create Database Configuration

In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create inc/config.php file on your project and put bellow code:

config.php

<?php
   
   // Database configuration    
   define('DBSERVER', 'localhost');
   define('DBUSERNAME', 'root');
   define('DBPASSWORD', '');
   define('DBNAME', 'webscodex');
  
   // Create database connection 
   $con = new mysqli(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
    
   // Check connection 
   if ($con->connect_error) { 
      die("Connection failed: " . $con->connect_error); 
   }
   
?>

Create HTML Page to display image with checkbox

In this file we will fetch product image from database and display on page with checkbox. click on the checkbox to download button images or single image in zip format.

index.php

<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Create and Download a Zip file with PHP</title>
        <!-- Bootstrap CSS -->
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    </head>
<body>
    <div class="container" style="background:#e6e6e6;padding-bottom: 20px;">
        <div class="py-5 text-center">
            <h2>Create and Download a Zip File with PHP</h2>
        </div>
        <form action="create_zip_download.php" method="POST">
        	<div class="row">
	        	<?php
	                // Database configuration    
	                require "inc/config.php";

	                $sql = "SELECT * FROM products WHERE status = '1' order by id DESC";
	                $query = $con->query($sql);
	                if ($query->num_rows > 0) {
	                    while ($row = $query->fetch_assoc()) {
	            ?>
	            <div class="col-md-4">
	                <div class="card d-flex justify-content-between align-items-center">
	                	<img src="images/<?php echo $row['image']?>" style="width:350px; height: 250px;">
	                </div>
					<div class="form-group form-check">
				      	<label class="form-check-label">
				        	<input class="form-check-input" type="checkbox" name="checkbox[]" 
				        	value="<?php echo $row['id']?>"><?php echo $row['product_name']?>
				      	</label>
				    </div>
	            </div>
	            <?php } } ?>
	            <div class="col-md-12 form-group text-center">
	            	<button type="submit" class="btn btn-primary" name="submit">Download</button>
	            </div>
        	</div>
        </form>
    </div>
</body>
</html>
Create Zip files and Download Zip file in PHP Code

Download Zip File from database

In this file we will download files in zip format. when we are check the checkbox and click on the download button then download the file in dynamically from database.

create_zip_download.php

<?php
	// Database configuration    
	require "inc/config.php";

	if (isset($_POST['submit'])) {
		$ids  = implode(",", $_POST['checkbox']);
		$query = "SELECT * FROM `products` WHERE id IN ($ids)";
		$reqult = $con->query($query);

		//Files path
		$filePath = 'images/';
		$zipFileName = "myZipFile.zip";

        if ($reqult->num_rows > 0) {
            while ($row = $reqult->fetch_assoc()) {
            	$filename = $row['image'];
            	convertFileZipAndDownload($filename, $zipFileName, $filePath);
            }
       	}
	}

	// CREATE FUNCTION FOR CREATE FILE IN ZIP AND DOWNLOAD
	function convertFileZipAndDownload($fileNames, $zipFileName, $filePath)
	{
	    $zip = new \ZipArchive();
	    //create the file and throw the error if unsuccessful
	    if ($zip->open($zipFileName, ZIPARCHIVE::CREATE )!==TRUE) {
	        exit("cannot open <$zipFileName>\n");
	    }
	    //add each files of $file_name array to archive
	    foreach($fileNames as $files)
	    {
	        $zip->addFile($filePath.$files,$files);
	    }
	    $zip->close();
	    
	    //then send the headers to force download the zip file
	    if(!empty($zipFileName) && file_exists($filePath)){ 
		    // Define headers 
		    header("Cache-Control: public"); 
		    header("Content-Description: File Transfer"); 
		    header("Content-Disposition: attachment; filename=$zipFileName"); 
		    header("Content-Type: application/zip"); 
		    header("Content-Transfer-Encoding: binary"); 
		    // Read the file 
		    readfile($zipFileName); 
		    exit; 
		}else{ 
		    echo 'The file does not exist.'; 
		}
	}

?>

Conclusion

In this article, I have explain the process of How to create download zip file using PHP with mysqli. I have tried to very simple way to implement to download file dynamically from database. You can easily extend the functionality according to your needs. To get all the necessary files, download the source code.

You can always support by sharing on social media or recommending my blog to your friends and colleagues.  If you have any suggestions or problems about this tutorial, please comment on the  form below.😊

Leave a Reply

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