PHP - How to create zip file and download using ZipArchive ?

By Hardik Savani | September 24, 2017 | Category : PHP

Today, i am going to share with you how to create zip file using ZipArchive then give for download. So here i will give you very simple example to do this.

We may require to create zip archive file using php code. We need to add some photos, docs etc on that zip file then give download. So here i am going to make very simple function createZip() that will help to create zip archive file. Using this function you have to simple pass array of file, docs, picture with path. So here i make very simple index.php file and you have to just copy that and run it.

Make sure you have two image file should available near index.php file:

1) demo1.jpg

2) demo2.jpg



/* create a compressed zip file */

function createZip($files = array(), $destination = '', $overwrite = false) {

if(file_exists($destination) && !$overwrite) { return false; }

$validFiles = [];

if(is_array($files)) {

foreach($files as $file) {

if(file_exists($file)) {

$validFiles[] = $file;




if(count($validFiles)) {

$zip = new ZipArchive();

if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {

return false;


foreach($validFiles as $file) {




return file_exists($destination);


return false;



$fileName = '';

$files_to_zip = ['demo1.jpg', 'demo2.jpg'];

$result = createZip($files_to_zip, $fileName);

header("Content-Disposition: attachment; filename=\"".$fileName."\"");

header("Content-Length: ".filesize($fileName));



Now you can run above whole file and check it.

I hope it can help you...

Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: