How to compress a Folder containing Sub-Folders and Files with PHP

Compress Folder PHP

Compress Folder PHP

Sometimes we need to compress entire folder including sub folders and files.To compress entire folder using ZipArchive() class you need to scan all folders and files.After assigning all files and folder in any variable you can easily add them to zip archive one by one.So here is the entire process to compress a folder containing sub-folders and files with PHP.
1.Choose path and output file name-Assign the relative path of folder which will be compressed in $folder variable and name of output folder in $zipvariable.

2.Create a ZipArchive object-Create an object say $zip of ZipArchive() class of PHP.

3.Create a ZipArchive and open it-Create a new zip archive and open it.

4.Read all files and folders-Read all files and folders of the directory and assign them into an array.

5.Add files and folder to archive-Add each and every files and folders to archive.

6.Close archive-Close archive and free CPU resources.

Here is the entire code to compress a folder containing sub-folders and files with PHP.


Incoming Search Terms:

  • php zip folder and subfolders