Home >Backend Development >PHP Tutorial >How to Create and Download a Multi-File ZIP Archive in PHP?

How to Create and Download a Multi-File ZIP Archive in PHP?

DDD
DDDOriginal
2024-12-23 19:42:15598browse

How to Create and Download a Multi-File ZIP Archive in PHP?

Creating ZIP Archives with Multiple Files in PHP

To download multiple files as a single ZIP archive using PHP, we can leverage the ZipArchive class.

Creating the ZIP Archive:

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

This code creates a ZIP archive named 'file.zip' and adds the specified files to it.

Streaming the ZIP Archive for Download:

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

These headers prepare the browser to display a download prompt and set the appropriate file name and size. By reading the ZIP archive file and streaming its contents, the browser can download it.

Additional Notes:

  • The 'Content-disposition' header forces the browser to present a download box to the user.
  • The 'Content-Length' header is optional, but it ensures compatibility with older browsers.
  • This approach allows for the dynamic creation of ZIP archives containing multiple files and their download.

The above is the detailed content of How to Create and Download a Multi-File ZIP Archive in 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