ItSolutionStuff.com

How to Create Zip Folder and Download in PHP?

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

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

PHP Ajax Form Validation Example Tutorial

Read Now →

PHP MySQL DataTables Server-side Processing Example

Read Now →

PHP Ajax Inline Editing using X-editable Bootstrap JS Example

Read Now →

PHP MySQL Integrate Fullcalendar Example Tutorial

Read Now →

PHP MySQL Image Gallery CRUD Example

Read Now →

PHP JQuery Ajax Image Upload Example Tutorial

Read Now →

PHP Ajax Infinite Scroll Pagination Example

Read Now →

PHP Ajax Dependent Dropdown List Example

Read Now →

PHP Bootstrap Autocomplete Tokenfield using Ajax Example

Read Now →

PHP Paypal Payment Gateway Integration Example

Read Now →

How to Create Zip File in Laravel?

Read Now →

How to Add JQuery Modal Popup in PHP?

Read Now →

PHP Download File from URL using CURL Request Example

Read Now →

Laravel Create JSON File & Download From Text Example

Read Now →