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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 03:36:13278browse

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

Creating a ZIP Archive to Download Multiple Files Using PHP

In web development, there are scenarios where you need to provide multiple files for download in a single, compressed package. PHP offers a convenient solution for this task using the ZipArchive class.

Utilizing the ZipArchive Class

To create a ZIP archive, follow these steps:

$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

Here, $zip represents the ZIP archive, and $zipname is the desired filename.

Adding Files to the Archive

Once the ZIP archive is created, you can add individual files to it:

foreach ($files as $file) {
  $zip->addFile($file);
}

Replace $files with an array containing the file paths or names.

Closing and Streaming the Archive

After adding all the necessary files, close the archive:

$zip->close();

Now, stream the archive to the client for download:

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

This code forces the browser to prompt a download box and designates the filename. The file size is specified to resolve compatibility issues in some browsers.

With these steps, you can easily create and download multiple files as a single ZIP archive using PHP.

The above is the detailed content of How to Create a Downloadable 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