Create New ZIP Archive

This section provides a tutorial example on how to create a new ZIP archive and add files into the archive using the ZipArchive class.

The best way to create a new ZIP archive is to use the "ZipArchive::CREATE" flag in the $zip->open() method. For example, the following code will create a new empty ZIP archive, if '/tmp/test.zip' does not exist. If '/tmp/test.zip' exists, it will be open to add new entries or extract entries. It fails only if '/tmp/test.zip' exists and is not a ZIP file.

$zip = new ZipArchive;
$zip->open('/tmp/test.zip',ZipArchive::CREATE);

Here is an example script that create a new ZIP archive and adds some files into the archive.

<?php
#  zip-create-new.php
#- Copyright 2009 (c) HerongYang.com. All Rights Reserved.

  $zip = new ZipArchive;
  echo "Creating test.zip:\n";
  $rc = $zip->open('/tmp/test.zip',ZipArchive::CREATE);
  if ($rc === TRUE) {
    echo "   test.zip opened\n";

    $file = 'dot.gif';
    if ($zip->addFile($file) === TRUE) {
      echo "   $file added\n";
    } else {
      echo "   Failed to add $file.\n";
    }

    $file = 'zip-create-new.php';
    if ($zip->addFile($file) === TRUE) {
      echo "   $file added\n";
    } else {
      echo "   Failed to add $file.\n";
    }

    $file = 'junk.jnk';
    if ($zip->addFile($file) === TRUE) {
      echo "   $file added\n";
    } else {
      echo "   Failed to add $file.\n";
    }

    $zip->close();
  } else {
    echo "   Failed to create test.zip with error: $rc\n";
  }
?>

Let's try it:

herong$ php zip-create-new.php
Creating test.zip:
   test.zip opened
   dot.gif added
   zip-create-new.php added
   Failed to add junk.jnk.

herong$ unzip -l /tmp/test.zip
Archive:  /tmp/test.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
       43  03-01-2020 14:15   dot.gif
      815  03-01-2020 15:17   zip-create-new.php
---------                     -------
      858                     2 files

Table of Contents

 About This Book

 Introduction and Installation of PHP

 Managing PHP Engine and Modules on macOS

 Managing PHP Engine and Modules on CentOS

 MySQLi Module - Accessing MySQL Server

 DOM Module - Parsing HTML Documents

 GD Module - Manipulating Images and Pictures

Zip Module - 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

 SOAP Module - Creating and Calling Web Services

 SOAP Module - Server Functions and Examples

 References

 Full Version in PDF/EPUB