Home > Backend Development > PHP Tutorial > How to Create and Download a ZIP Archive of Multiple Files Using PHP?

How to Create and Download a ZIP Archive of Multiple Files Using PHP?

Patricia Arquette
Release: 2024-12-14 17:14:12
Original
660 people have browsed it

How to Create and Download a ZIP Archive of Multiple Files Using PHP?

Creating a ZIP Archive from Multiple Files in PHP

Question: How can I download multiple files as a ZIP archive using PHP?

Solution:

To achieve this, you can leverage PHP's ZipArchive class. Here's how you can proceed:

  1. Create a ZIP Archive:

    $files = array('readme.txt', 'test.html', 'image.gif');
    $zipname = 'file.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE);
    Copy after login
  2. Add Files to the ZIP Archive:

    foreach ($files as $file) {
      $zip->addFile($file);
    }
    Copy after login
  3. Close the ZIP Archive:

    $zip->close();
    Copy after login
  4. Stream the ZIP Archive to the Client:

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

The first line in the streaming section specifies the Content-Type as a ZIP archive. The second line instructs the browser to display a download box for the user and assigns the filename file.zip. The third line calculates and sets the Content-Length header for older browsers that may encounter issues without knowing the file size in advance.

The above is the detailed content of How to Create and Download a ZIP Archive of Multiple Files Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template