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
Patricia ArquetteOriginal
2024-12-14 17:14:12660browse

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);
  2. Add Files to the ZIP Archive:

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

    $zip->close();
  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);

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!

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