Create ZIP Archive for Download

This section provides a tutorial example on how to create a ZIP archive in a temporary file with dymanic data and send it to Web browser as a download using the ZipArchive class.

If you have data items from database for Users to download from a Web server, you may want to ZIP them on the fly so users can download them in a single ZIP file.

Of course, the best option is to retrieve data items from database in memory, ZIP them in memory and send the ZIP to user's browser without creating any physical files on the Web server. However, this is not doable with the ZipArchive class, which does not support ZIP archive as file handles or pipes.

The next option is to retrieve data items from database in memory, ZIP them in a temporary file and remove it after sending it to user's browser. This can be done the following steps:

1. Create a unique file name in the system temporary directory as the ZIP file name:

$tmpDir = sys_get_temp_dir();
$zipFile = tempnam($tmpDir, "ZIP"); # ZIP is the prefix for temp name

2. Open the temporary file and the ZIP archive:

$zip->open($zipFile, ZipArchive::CREATE);

3. Retrieve data items from database and loop over each item.

4. Create an unique name for each item, and the item data to the ZIP archive as a string.

$itemData = ...; # based data from database
$itemName = ...; # based record ID from database
$zip->addFromString("$itemName", $itemData);

5. Close the ZIP archive, read the ZIP data back from the temporary file, and remove it immediately.

$zip->close();
$zipData = file_get_contents($zipFile);
unlink($zipFile);

6. Send the ZIP data to the Web browser.

Here is an example script that creates a new ZIP archive in temporary file with dynamic data items. The ZIP archive is then pushed to client browser.

<?php
#  zip-in-temp-file.php
#- Copyright 2009 (c) HerongYang.com. All Rights Reserved.
  $dir = "msg";
  $file = 'hello.txt';

  $tmpDir = sys_get_temp_dir();
  $zipFile = tempnam($tmpDir, "ZIP");

  $zip = new ZipArchive;
  error_log("Creating ZIP file $zipFile");
  $rc = $zip->open($zipFile, ZipArchive::CREATE);
  if ($rc === TRUE) {
    if ($zip->addEmptyDir($dir) === TRUE) error_log("$dir added");

    # this could be any data and muliple times
    if ($zip->addFromString("$dir/$file", 'Hello world!') === TRUE)
      error_log("$file added");

    $zip->close();
  } else {
    error_log("Failed to create ZIP with error: $rc");
  }

  $zipData = file_get_contents($zipFile);
  unlink($zipFile);

  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=Hello.zip");
  header("Content-Length: " . strlen($zipData));
  header("Cache-Control: no-cache");
  print($zipData);
?>

If you put the above script on a Web server and open it in Web browser. You will get a ZIP file, Hello.zip, downloaded.

Table of Contents

 About This Book

 Introduction and Installation of PHP

 PHP Script File Syntax

 PHP Data Types and Data Literals

 Variables, References, and Constants

 Expressions, Operations and Type Conversions

 Conditional Statements - "if" and "switch"

 Loop Statements - "while", "for", and "do ... while"

 Function Declaration, Arguments, and Return Values

 Arrays - Ordered Maps

 Interface with Operating System

 Introduction of Class and Object

 Integrating PHP with Apache Web Server

 Retrieving Information from HTTP Requests

 Creating and Managing Sessions in PHP Scripts

 Sending and Receiving Cookies in PHP Scripts

 Controlling HTTP Response Header Lines in PHP Scripts

 Managing File Upload

 MySQL Server Connection and Access Functions

 Functions to Manage Directories, Files and Images

 SOAP Extension Function and Calling Web Services

 SOAP Server Functions and Examples

 Localization Overview of Web Applications

 Using Non-ASCII Characters in HTML Documents

 Using Non-ASCII Characters as PHP Script String Literals

 Receiving Non-ASCII Characters from Input Forms

 "mbstring" Extension and Non-ASCII Encoding Management

 Managing Non-ASCII Character Strings with MySQL Servers

 Parsing and Managing HTML Documents

 Configuring and Sending Out Emails

 Image and Picture Processing

Managing ZIP Archive Files

 The ZipArchive Class

 Create New ZIP Archive

 Extract Files from ZIP Archive

 Create ZIP Archive with Directory

Create ZIP Archive for Download

 Managing PHP Engine and Modules on macOS

 Managing PHP Engine and Modules on CentOS

 Archived Tutorials

 References

 Full Version in PDF/EPUB