Home  >  Article  >  Backend Development  >  How to create zip file and download using PHP ZipArchive?

How to create zip file and download using PHP ZipArchive?

藏色散人
藏色散人Original
2019-02-28 13:19:593994browse

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

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);

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!

Statement:
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