How to create dynamic zip Archive file in PHP?

How to create dynamic zip Archive file in PHP
Written by Yogesh Koli

In this tutorial I am going to provide solution on creating dynamic zip archive file in PHP, look at the following features of this tutorial.

Tutorial Features

  • Create Zip archive File
  • Add Files dynamically
  • Save Zip archive File on server
  • Download  recently generated Zip Archive File From the Server

Let’s assume you have a task that required to collect all uploaded images, documents or text files of the user and zip those collection of document into on bundle and keep it ready for download.

Before diving into the tutorial if your running on PHP 7 and don’t have zip library installed then use following command to get it installed for ubuntu/linux users.

Step 1: Create new PHP Project

Create new PHP project directory into your PHP environment, you can skip this step if you are trying to implement this feature into your existing project.

Here I have created my PHP project and now I am going to add few dummy files to user for this demo, you can look at the following project folder structure to get idea

Project Folder Structure

Project Folder Structure

So I as you see in the above folder structure we have bunch of text file ready to execute the demo, let’s move on to the next step

Step 2: Create Zip File with Existing Files

Assume that you have file-1.txt, file-2.txt are uploaded by you active users, now they want to download all files in bundle, that is our next step to simply add requested files into zip archive file and download a created zip files.

Let’s update our index.php file to add script to create our zip file and add files into it.


Step 3: Zip File Download Script:

In this step we are going to write a php script to able to load a particular file from the folder and making it ready for download.

so here we have our zip file stored into the files folder next we just need to write a php script to open that file from the folder and download as an attachment.

Go ahead and open index.php file and add following script after closing of the zip object:

Complete Script:

Here is complete script from index.php file, go ahead and run this file into your server of local development environment and let me know if this script helps you into your project.

Thank you for being a valuable reader of iTech Empires, let me know if this solution works for you in your project by using comment box below.

Keep Learning, Happy Coding.

See you in next tutorial.

About the author

Yogesh Koli

Yogesh Koli is a software engineer & a Blogger lives in India. He's driven by an addiction to learning and a love for adventure. he has 5+ years of experience working with the front-end, back-end, web application development, and system design.


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of