Download folder as zip file in php

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

images/

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

And this is mine generate_zip.php:


How to gather all the files from "images/" folder, except "generate_zip.php", and make it a downloadable .zip? In this case the "images/" folder always have a different image. Is that possible?

T.Todua

50.1k19 gold badges217 silver badges213 bronze badges

asked Jul 17, 2013 at 19:26

Ygor MontenegroYgor Montenegro

6841 gold badge12 silver badges26 bronze badges

0

======= Working solution !======

includes all sub-folders:

new GoodZipArchive['path/to/input/folder',    'path/to/output_zip_file.zip'] ;

at first, include this piece of code.

answered Oct 18, 2013 at 14:17

8

this will ensure a file with .php extension will not be added:

   foreach [$files as $file] {
        if[!strstr[$file,'.php']] $zip->addFile[$file];
    }

edit: here's the full code rewritten:


answered Jul 17, 2013 at 19:28

skrilledskrilled

5,2522 gold badges23 silver badges47 bronze badges

9

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


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.

answered Jul 17, 2013 at 19:53

way2vinway2vin

2,3211 gold badge20 silver badges15 bronze badges

I went with way2vin's solution. However I had to replace

$zip->addFile["{$file}"];

with

$zip->addFromString[basename[$file], file_get_contents[$file]];

which did the trick. Found this here: Creating .zip file

answered Dec 26, 2019 at 11:55

change your foreach loop to this to except generate_zip.php

 foreach [$files as $file] {
     if[$file != "generate_zip.php"]{
        $zip->addFile[$file];
     }
 }

answered Jul 17, 2013 at 19:45

shyammakwana.meshyammakwana.me

5,3242 gold badges26 silver badges49 bronze badges

Chủ Đề