Blog
Download Selected Files as ZIP Using a PHP Form
Let visitors choose several files and download them together with a PHP form. Instead of starting three separate downloads, the server builds one ZIP archive containing only the selected items.
This tutorial uses PHP’s ZipArchive class, an HTML checkbox form, and a server-side allowlist. The complete project includes three public sample files, responsive styling, error messages, and temporary-file cleanup.
Try the file selection demo
Select any combination of the sample files below, then open the downloaded archive to check its contents. Select all and Clear selection help you try different combinations.
About this live preview: the embedded demo creates a real ZIP in your browser using JavaScript. The downloadable project’s index.php implements the same selection flow on a PHP server using ZipArchive. The PHP form works without JavaScript.
Select your files
Choose one or more sample files and get them in one ZIP archive.
Enable JavaScript for this browser preview, or run the PHP project included in the source ZIP.
What you need
Use PHP 8 or later with the ZIP extension enabled. The server must be able to read the sample files and write to its temporary directory. You do not need Bootstrap, jQuery, Composer, or a database.
selected-files-zip-demo/
index.php
style.css
files/
README.txt
data.csv
styles.css
preview.html
preview.js
README.md
1. Send file IDs from an HTML form
Give each checkbox the name files[]. PHP receives checked values as an array; unchecked boxes are omitted. Use short identifiers as values rather than accepting filenames or filesystem paths from the browser.
<form method="post" action="index.php">
<fieldset>
<legend>Files to include</legend>
<label><input type="checkbox" name="files[]" value="readme"> README.txt</label>
<label><input type="checkbox" name="files[]" value="data"> data.csv</label>
<label><input type="checkbox" name="files[]" value="styles"> styles.css</label>
</fieldset>
<button type="submit">Download selected ZIP</button>
</form>
2. Map IDs to approved files
The server decides what each ID means. A request containing ../../some-file must never become a filesystem path. Keep a fixed catalog, check that the submitted value is an array, and reject unknown or non-string values before creating an archive.
$catalog = [
'readme' => ['path' => __DIR__ . '/files/README.txt', 'name' => 'README.txt'],
'data' => ['path' => __DIR__ . '/files/data.csv', 'name' => 'data.csv'],
'styles' => ['path' => __DIR__ . '/files/styles.css', 'name' => 'styles.css'],
];
$requested = $_POST['files'] ?? [];
$selected = [];
if (!is_array($requested) || count($requested) < 1
|| count($requested) > count($catalog)) {
$error = 'Select between one and three files.';
} else {
foreach ($requested as $id) {
if (!is_string($id) || !isset($catalog[$id])) {
$error = 'One of the selected files is not available.';
break;
}
$selected[$id] = $catalog[$id];
}
}
Keying the selection by ID also prevents duplicate entries. Before continuing, check class_exists(ZipArchive::class), is_file(), and is_readable(). The full source handles these cases with readable messages.
3. Create a unique temporary archive
Use tempnam() to give each request a different temporary file. A shared filename such as Download.zip can cause concurrent requests to overwrite each other. Add each approved file with a clean archive entry name, then close the archive before sending it.
$tempFile = tempnam(sys_get_temp_dir(), 'swc_zip_');
if ($tempFile === false) {
throw new RuntimeException('Temporary file creation failed.');
}
register_shutdown_function(static function () use ($tempFile): void {
if (is_file($tempFile)) { unlink($tempFile); }
});
$zip = new ZipArchive();
if ($zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
throw new RuntimeException('Archive creation failed.');
}
foreach ($selected as $file) {
if (!$zip->addFile($file['path'], $file['name'])) {
throw new RuntimeException('Adding a file failed.');
}
}
if (!$zip->close()) {
throw new RuntimeException('Archive close failed.');
}
These snippets explain the main steps. Use the downloadable index.php for the integrated handler, including validation, exception handling, and closing the archive when an operation fails.
4. Send download headers before HTML
The request handler must run before the page markup. Sending HTML, a byte-order mark, or stray whitespace first can corrupt the archive or trigger a “headers already sent” warning. A fixed download filename keeps the response header simple.
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="selected-files.zip"');
header('Content-Length: ' . filesize($tempFile));
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');
readfile($tempFile);
exit;
The registered shutdown function removes the temporary archive after the response finishes. The original sample files remain available for later requests.
Run the PHP project locally
Extract the source ZIP and open a terminal in the selected-files-zip-demo folder. Start PHP’s development server:
php -S 127.0.0.1:8000
Visit http://127.0.0.1:8000/index.php, select files, and submit the form. Opening index.php directly as a local file does not execute PHP. To try the browser-only preview without a server, open preview.html instead.
Common questions
Why is ZipArchive not found?
The ZIP extension is missing or disabled in the PHP runtime handling the request. Check php -m for the command-line runtime and enable ZIP in the relevant PHP configuration. Your web server may use a different configuration from the terminal.
Why does my ZIP contain a folder path?
The second argument to addFile() controls the name inside the archive. Pass a clean name such as README.txt instead of exposing your server directory structure.
Can I use this for private documents?
This example serves public sample files. For private documents, check the visitor’s identity and permission for every selected item, keep documents outside the public web directory, and set limits suitable for your application. The allowlist is still necessary.
Does the browser preview compress the files?
The preview writes valid ZIP entries using the stored, uncompressed method. It demonstrates selection and packaging. The PHP project uses ZipArchive’s default compression behavior.
Download the complete project
Get the PHP form and handler, three sample files, shared stylesheet, browser preview, and setup instructions in one archive.
Conclusion
A checkbox form and ZipArchive make multi-file downloads straightforward. Validate the selected IDs, create a separate temporary archive for each request, send headers before output, and clean up afterward.
References: PHP ZipArchive manual, ZipArchive::addFile(), and tempnam().