How to Create ZIP File in PHP

Learn how to create ZIP file using PHP. In the previous post, we will see how to compress the image before uploading in PHP.

Zip file normally used to compress folder and files and create an archive file which allows downloading at all files at once.

In PHP we can create ZIP file dynamically and save archive files on the server easily.

You can archive the full directory recursively to the ZIP file in PHP. In this tutorial, we will show you the best practices to make ZIP file from folder using PHP.

Example: Create ZIP File Using PHP ZipArchive

Step 1: Add ZipArchiver Class:

The ZipArchiver class creates ZIP file from a folder on the server with the help of PHP ZipArchive.

zipDir(): This function creates a Zip of a folder recursively including the parent directory.

$sourcePath: Folder path to be zipped.

$outZipPath: Path to save the zip file on the server.

dirToZip(): It is a helper function of ZipArchiver class that adds folders and files to the zip file.

Create a ZipArchiver.class.php

Step 2: Create index.php to make ZIP in PHP

Include ZipArchiver.class.php to archive all sub-folder and files of the given folder and make ZIP file from the script in PHP.

  • Include ZipArchive class and initialize it.
  • Mention the directory path, which you want to archive as a ZIP file
  • Add path to save the ZIP file on the server
  • Call the zipDir() function to make ZIP file.

index.php

 

Recommended Posts For You

About Harish

I am professional web developer and blogger. Use this blog to share own api and other web development experience with you. I do accept paid work. Write to me at - [email protected]

View all posts by Harish