How to Create Zip Folder and Download in PHP?

By Hardik Savani May 14, 2024 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

Example:

<?php


/* 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) {

$zip->addFile($file,$file);

}


$zip->close();

return file_exists($destination);

}else{

return false;

}

}


$fileName = 'my-archive.zip';

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

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


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

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

readfile($fileName);


?>

Now you can run above whole file and check it.

I hope it can help you...

Shares