How to create zip file and download in Laravel using ZipArchive class
In this article we will learn how to create zip of multiple file and download it using ZipArchive class of PHP . We will take an example where we will retrieve image names from DB and images are available in our local project directory and then we will convert it to Zip .
ZipArchive class provides lots of built-in methods to work with zip files but in this example we will use some basic methods of ZipArchive class to convert our multiple files to zip file .
Some of the basic ZipArchive class methods are like ZipArchive::CREATE which is used to create a zip file , $zip->open() method basically takes two parameter that is zip file name and the ZipArchive::CREATE method . Similarly some other methods are $zip->addFile() used to add multiple file to the zip and $zip->close() this method is used to close the zip file after you added all the file inside the zip .
Lets understand how to create zip and download it via example .
Step 1 - Create Route :
Route::get('/downloadzip','UserController@downloadZip')->name('download-zip');
Step 2 - Code in Controller :
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\ImgUpload; use ZipArchive; use File; class UserController extends Controller { /** * Function to get all images from DB */ public function downloadZip() { $data = ImgUpload::all(); foreach($data as $key => $value) { $imgarr[] = "storage/image". '/' . $value->image; } $ziplink = $this->converToZip($imgarr); return $ziplink; } /** * Function to covert all DB files to Zip */ public function converToZip($imgarr) { $zip = new ZipArchive; $storage_path = 'storage/image'; $timeName = time(); $zipFileName = $storage_path . '/' . $timeName . '.zip'; $zipPath = asset($zipFileName); if ($zip->open(($zipFileName), ZipArchive::CREATE) === true) { foreach ($imgarr as $relativName) { $zip->addFile($relativName,"/".$timeName."/".basename($relativName)); } $zip->close(); if ($zip->open($zipFileName) === true) { return $zipPath; } else { return false; } } } }
Step 3 - Now hit your Route :
After hitting your route you will get the link of the zip file created on the folder you specified . Now you can use the link to download the zip file .
Step 4 - Download file :
Now you can use the URL to download your file .
Created Zip file :
Thank you for reading this article 😊
For any query do not hesitate to comment 💬