Create Zip File of Multiple Uploaded Files using PHP

Last modified on April 29th, 2019 by Vincy.

Zip file is unarguably the popular file format across platforms. We should be well equipped to handle it programmatically. We will see about how to create a zip file of multiple files using PHP for the use-case of multiple file upload.

We will have a HTML form to facilitate upload of multiple files. Then on successful upload, those files will be zipped as a single file using PHP. Let us walk through it.

For uploading multiple files, the HTML form must contain an array of file input fields. Previously, we have seen variety of PHP examples for uploading files

In this example, we are going to use the knowledge that we have gained from the previous tutorial code for providing multiple file upload option. Thereby, we will step forward to create the zip file of multiple files uploaded by the user.

In this example, there are two main files index.php and upload.php. The file index.php contains HTML code to create the form with multiple file input option. The upload.php file contains PHP script to handle the file upload and to create zip file.

For customizing this code, we need to be sure about target path where the files has to be uploaded and the compressed zip is to be created. As for this example, the zip file will be created in the uploads folder and it is in the root.

Once the multiple files are uploaded and moved to the target successfully,  then a download link will be displayed to the browser to let the user to download the created zip file.

What is inside?

  1. Uses of compressing the uploaded files into a zip
  2. Existing libraries to create zip of multiple files
  3. About ZipArchive plugin
  4. Code implementation to create zip file of multiple uploaded files
  5. File Structure
  6. HTML with file upload and zip download option
  7. Create zip using PHP ZipArchive
  8. Create Zip File of Multiple Uploaded Files PHP example output

Uses of compressing the uploaded files into a zip

Creating the zip file consisting of multiple files will be helpful in many use case scenarios. Some of them are listed below.

  • While exporting collection of photos as a zip from the gallery or any kind of digital album the extracted data could be downloaded in the form of compressed zip.
  • In a job portal the user uploaded qualification, curriculum vitae documents are compressed into a zip format that can be downloadable by admin.
  • Online stores selling intellectual products are generally in the form of zip containing the software product files.

Existing libraries to create zip of multiple files

There are many PHP, Javascript libraries, plugins available in the market to create zip. For example, JSZip library is used to create zip file and also support to edit the zip content.

The JSZip is a JavaScript library which helps to create, read and edit zip files. It builds the zip file archives with the help of the library API object. Then, it creates the zip target folder programatically to store the created zip file.

In this example, I have used PHP ZipArchive class to create zip file consisting of multiple uploaded files. In the next section, let’s see the merits and usage methodologies of this PHP class.

About PHP ZipArchive class

The PHP ZipArchive class allows to set file name, number of files, comments and more properties about the file archive. 

It contains methods to create zip file directory, add files to the zip archive, empty directory and more. Some of these functions are used in this example to create zip with the number of files uploaded by the user.

Code implementation to create zip file of multiple uploaded files

For implementing the process of creating zip file with the uploaded files I have used the PHP ZipArchive class. This class is loaded in the PHP code and loaded with the uploaded file binaries.

In this example, the user can choose and upload multiple files via a HTML form. The file data are posted to the PHP and compressed into a ZIP format by using the PHP ZipArchive class.

The created ZIP and uploaded files are stored in a specified target. Once the ZIP is created, a download link will be shown in the output to download the ZIP file to the browser.

File Structure

All these implementation can be done with the below simple file structure of this example. The minimum number of files shown in this image describes the simplicity of this example.

Create Zip of Multiple Uploaded Files PHP Example File Structure

HTML with file upload and zip download option

In this section, we are going to create the HTML interface to upload multiple files. Also it contains the HTML markup to show the download option for the created zip.

In this example, I have used Bootstrap for developing the file upload interface. With the default HTML multiple property a file input field in this interface is used to choose multiple files.

Once the files have chosen and uploaded to the server side, then the PHP script will handle the file binaries to compressed into a zip archive.

<html>
<head>
    <title>Create Zip File of Multiple Uploaded Files using PHP</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

</head>
<body>
    <?php include 'upload.php'; ?>
    <div class="row">
    	<div class="page-container row-12">
    		<h4 class="col-12 text-center mb-5">Create Zip File of Multiple Uploaded Files </h4>
    		<div class="row-8 form-container">
            <?php 
            if(!empty($error)) { 
            ?>
    			<p class="error text-center"><?php echo $error; ?></p>
            <?php 
            }
            ?>
            <?php 
            if(!empty($success)) { 
            ?>
    			<p class="success text-center">
            Files uploaded successfully and compressed into a zip format
            </p>
            <p class="success text-center">
            <a href="uploads/<?php echo $success; ?>" target="__blank">Click here to download the zip file</a>
            </p>
	    	    <?php 
            }
            ?>
		    	<form action="" method="post" enctype="multipart/form-data">
				    <div class="input-group">
						<div class="input-group-prepend">
						    <input type="submit" class="btn btn-primary" value="Upload">
						</div>
						<div class="custom-file">
						    <input type="file" class="custom-file-input" name="img[]" multiple>
						    <label class="custom-file-label" >Choose File</label>
						</div>
					</div>
				</form>
				
    		</div>
		</div>
	</div>
</body>
</html>

Create zip using PHP ZipArchive

ZipArchive is PHP class that used to work with zip files. Make sure zip extension is enabled in your PHP settings.

In the below PHP code the ZipArchive instance is created and used to invoke methods to create zip file.

After creating the zip file, the user uploaded files are moved to the zip archive. In this code, the uploaded files are also moved to a target folder as specified.

Previously, we have seen how to upload files to a target folder using PHP. The PHP move_uploaded_file($filename, $destination) function is used to do this. It requires the name of the file to be uploaded and the destination path.

Once the output zip file is created with the uploaded files, the zip instance is destructed by calling the ZipArchive close method. After that, the created zip file source path is sent as the response. 

If no files are chosen then the server side validation error message will be returned. The error and success response is used to show suitable acknowledgement to the user.

<?php
if ($_FILES && $_FILES['img']) {
    
    if (!empty($_FILES['img']['name'][0])) {
        
        $zip = new ZipArchive();
        $zip_name = getcwd() . "/uploads/upload_" . time() . ".zip";
        
        // Create a zip target
        if ($zip->open($zip_name, ZipArchive::CREATE) !== TRUE) {
            $error .= "Sorry ZIP creation is not working currently.<br/>";
        }
        
        $imageCount = count($_FILES['img']['name']);
        for($i=0;$i<$imageCount;$i++) {
        
            if ($_FILES['img']['tmp_name'][$i] == '') {
                continue;
            }
            $newname = date('YmdHis', time()) . mt_rand() . '.jpg';
            
            // Moving files to zip.
            $zip->addFromString($_FILES['img']['name'][$i], file_get_contents($_FILES['img']['tmp_name'][$i]));
            
            // moving files to the target folder.
            move_uploaded_file($_FILES['img']['tmp_name'][$i], './uploads/' . $newname);
        }
        $zip->close();
        
        // Create HTML Link option to download zip
        $success = basename($zip_name);
    } else {
        $error = '<strong>Error!! </strong> Please select a file.';
    }
}

Create Zip File of Multiple Uploaded Files PHP example output

Below screenshots shows the success and failure responses of this PHP example. In the success response, it will show the text message with an option to download the created zip file.

Create Zip File of Multiple Uploaded Files Output

File Upload Validation for Creating Zip

Conclusion

This simple code to create zip file using PHP will be useful for you while developing a web application consisting of this requirement. File handling in PHP is heavily supported by its in-built functions and classes available with it core.

It is simple and easy with PHP core classes.

We have seen the possible scenarios where the create zip with multiple uploaded files example will be useful. This may give a spark to the web developers searching for solution in such scenarios.

With Bootstrap look and feel the UI has the combined unit of elements to choose files, upload and download the zip output. If you want to make it simple, you can detach the Bootstrap library from the example and use the skeleton to make it with your application tone.

Hope this article will be helpful for you the readers who are making my days always. Feel free to share your comments, alternative approaches on my code.

Download

↑ Back to Top

Share this Article