Downloading multiple files at a time is a mess and we face this situation many times. Creating Zip using php can help you to overcame from this situation. In this tutorial we will discuss how to create zip file in php.
For using zip we have php class ZIPArchive which we are going to use. We will follow some steps to do it. Easy task you can find the working files at the bottom.
Suppose we have a folder and some image files in that folder. Now we will create the folder under the zip and add those files to the new folder.
<?php $directory="myimages"; createZip($directory); function createZip($directory){ echo "Creating zip file ....."; $zip= new ZipArchive(); //Initialising the zip archive if($zip->open("myzip.zip", ZipArchive::CREATE)!== TRUE){die ("Could not open archive");} else { $myfile=array(); $i="1"; if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { if($file==".."||$file==""){} else{array_push($myfile, $file);} } // print_r($myfile); foreach ($myfile as $value) { if($value=="."){} else{$zip->addFile($directory."/".$value);} } closedir($handle);} echo "<br/>Zip Created";} $zip->close();} ?>
Let me discuss the above code. We have a directory “myimages” in which we have some images.
We will call our “createZip()” function which will do the rest work.
$zip=new ZipArchive(); //Above code will initialise the zip archive.
We will try to open the zip file if it is exists it will be created
$zip->open("myzip.zip", ZipArchive::CREATE)!== TRUE //After the creation it will open the zip for adding the files.
Getting the file names which are inside the folder and adding them to $myflie array.
$myfile=array(); // Array for store the file names $i="1"; if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { if($file==".."||$file==""){} else{array_push($myfile, $file);} }
Now we will add all the files to the ZIP.
//$zip->addFile($directory."/".$value) // We will use the addFile function to add the files and provide the path and file name of file.
foreach ($myfile as $value){ if($value=="."){} else{$zip->addFile($directory."/".$value);} }
We will close the handle and the zip
closedir($handle); // It will close the file handler $zip->close(); // It will close the zip archive
When you call the function you will see a zip is created with the name “myzip.zip” having the folder and when you open that folder you will see the images.
Thank you for reading how to create zip file in php please let us know and provide your reviews. If you found any issue with the code please comment. You can download the files form the below
[wpdm_file id=6 title=”true” template=”facebook ” ]
Hi, Vivek,
your post was rather helpful, thank you! I especially like that you explain the steps you take.
Best regards,
Elisabeth