Home > Article > Backend Development > How to create zip file and download using PHP ZipArchive?
During the project development process, we may need to implement the function of creating zip files and providing downloading. So here we can use the ZipArchive class to create a zip file and then download it.
Let me give you a simple example. Sometimes we need to use php code to create a zip archive file, add some photos, documents, etc. to the zip file, and then provide it for download. Here we will create a very simple method createZip() which will help create zip archive files. Using this method, you can simply pass an array of files, documents, images and paths.
Related recommendations: "[zip file library] 10 php zip file library download"
Below I wrote a very simple index.php file example , you can copy it directly and run it locally for testing.
Make sure there is an available image file in the index.php file:
1)demo1.jpg 2)demo2.jpg
The code example is as follows:
<?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);
This article is about using PHP ZipArchive to create zip files And the downloading method is introduced, I hope it will be helpful to friends in need!
The above is the detailed content of How to create zip file and download using PHP ZipArchive?. For more information, please follow other related articles on the PHP Chinese website!