ZIP all files in directory and download generated .zip

后端 未结 6 1592
逝去的感伤
逝去的感伤 2020-12-04 18:12

Well, first of all, this is my folder structure:

images/

image1.png
image11.png
image111.png
image223.png
generate_zip.php

And this is min

6条回答
  •  一生所求
    2020-12-04 18:33

    Since you just need specific files from a directory to create ZipArchive you can use glob() function to do this.

    open($download, ZipArchive::CREATE);
        foreach (glob("images/*.png") as $file) { /* Add appropriate path to read content of zip */
            $zip->addFile($file);
        }
        $zip->close();
        header('Content-Type: application/zip');
        header("Content-Disposition: attachment; filename = $download");
        header('Content-Length: ' . filesize($download));
        header("Location: $download");
     ?>
    

    Don't use glob() if you try to list files in a directory where very much files are stored (more than 100.000). You get an "Allowed memory size of XYZ bytes exhausted ..." error.

    readdir() is more stable way.

提交回复
热议问题