How to Create Zip Folder and Download in 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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. 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, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- PHP Ajax Form Validation Example Tutorial
- PHP MySQL DataTables Server-side Processing Example
- PHP Ajax Inline Editing using X-editable Bootstrap JS Example
- PHP MySQL Integrate Fullcalendar Example Tutorial
- PHP MySQL Image Gallery CRUD Example
- PHP JQuery Ajax Image Upload Example Tutorial
- PHP Ajax Infinite Scroll Pagination Example
- PHP Ajax Dependent Dropdown List Example
- PHP Bootstrap Autocomplete Tokenfield using Ajax Example
- PHP Paypal Payment Gateway Integration Example
- How to Create Zip File in Laravel?
- How to Add JQuery Modal Popup in PHP?
- PHP Download File from URL using CURL Request Example
- Laravel Create JSON File & Download From Text Example