Download multiple files as a zip-file using php

后端 未结 4 1501
醉梦人生
醉梦人生 2020-11-22 16:16

How can I download multiple files as a zip-file using php?

4条回答
  •  忘了有多久
    2020-11-22 16:43

    You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:

    $files = array('readme.txt', 'test.html', 'image.gif');
    $zipname = 'file.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE);
    foreach ($files as $file) {
      $zip->addFile($file);
    }
    $zip->close();
    

    and to stream it:

    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: ' . filesize($zipname));
    readfile($zipname);
    

    The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.

提交回复
热议问题