PHP – How to create zip file and download multiple files using ZipArchive ?
In this post we will give you information about PHP – How to create zip file and download multiple files using ZipArchive ?. Hear we will give you detail about PHP – How to create zip file and download multiple files using ZipArchive ?And how to use it also give you demo for it if it is necessary.
In this PHP Tutorial, I am going to tell you how to create zip file using PHP’s ZIP class “ZipArchive”.
You can use this example to download multiple files at the same time by creating zip file, you can simply add the downloading files in a zip with the help of PHP’s ZIP class.
In this example, I will use open()
method to open or create any zip file and addFile()
method is used to add files to archive from the given path and close()
method is used to close zip file safely.
Example:
<?php /* create a compressed zip file */ functioncreateZipArchive($files=array(), $destination='', $overwrite=false) { if(file_exists($destination) &&!$overwrite) { returnfalse; } $validFiles=array(); if(is_array($files)) { foreach($filesas$file) { if(file_exists($file)) { $validFiles[] =$file; } } } if(count($validFiles)) { $zip=new ZipArchive(); if($zip->open($destination,$overwrite? ZIPARCHIVE::OVERWRITE: ZIPARCHIVE::CREATE) ==true) { foreach($validFilesas$file) { $zip->addFile($file,$file); } $zip->close(); returnfile_exists($destination); }else{ returnfalse; } }else{ returnfalse; } } $fileName='myzipfile.zip'; $files=array('uploads/profile1.jpeg', 'uploads/profile2.jpeg'); $result= createZipArchive($files, $fileName); header("Content-Disposition: attachment; filename="".$fileName."""); header("Content-Length: ".filesize($fileName)); readfile($fileName); ?>
You have to set header correctly to force download. You can pass the array of files in createZipArchive()
function.
Try it..
Hope this code and post will helped you for implement PHP – How to create zip file and download multiple files 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