PHP – How to create zip file and download using ZipArchive ?
In this post we will give you information about PHP – How to create zip file and download using ZipArchive ?. Hear we will give you detail about PHP – How to create zip file and download using ZipArchive ?And how to use it also give you demo for it if it is necessary.
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…
Hope this code and post will helped you for implement PHP – How to create zip file and download using ZipArchive ?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs