How to create zip file and download using PHP ZipArchive?

藏色散人
Release: 2023-04-05 12:42:01
Original
4052 people have browsed it

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.

How to create zip file and download using PHP ZipArchive?

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
Copy after login

The code example is as follows:

 <?php


/* create a compressed zip file */
function createZip($files = array(), $destination = &#39;&#39;, $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 = &#39;my-archive.zip&#39;;
$files_to_zip = [&#39;demo1.jpg&#39;, &#39;demo2.jpg&#39;];
$result = createZip($files_to_zip, $fileName);


header("Content-Disposition: attachment; filename=\"".$fileName."\"");
header("Content-Length: ".filesize($fileName));
readfile($fileName);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template