In this example, I will explain how to create a zip file of multiple files using PHP.
Create below function to create a zip file from multiple files.
function createZipFromFiles($files, $zipName) { $zip = new ZipArchive(); $zip->open($zipName, ZipArchive::CREATE); foreach ($files as $file) { $zip->addFile($file); } $zip->close(); }
The above function takes two arguments, $files
– an array of files with full path and $zipName
– the zip file name that has extension .zip
.
Usage example
Here I will show you how to use the above function to create an archive or zip file.
$folder = 'uploads/'; $files = array($folder . 'a.jpg', $folder . 'b.jpg'); $zipName = $folder . 'Archive_' . time() . ".zip"; createZipFromFiles($files, $zipName);
So first the a.jpg
and b.jpg
are kept into folder 'uploads'
and $files
array is built using those files.
Then I define a $zipName
using current time so every time a unique zip name is generated.
Then I simply call the createZipFromFiles()
function to create the zip file.
Thanks for reading.