Extract Files from ZIP Archive

This section provides a tutorial example on how to open an existing ZIP archive and extract files from the archive using the ZipArchive class.

The easiest way to extract files from an ZIP archive to use the $zip->extractTo() method. For example, the following code extracts 'dot.gif' from '/tmp/test.zip' into the '/tmp' directory.

$zip = new ZipArchive;
$zip->open('/tmp/test.zip');
$zip->extractTo('/tmp','dot.gif');

Here is an example script that opens an existing ZIP archive and extracts files from the archive.

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

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

    $file = 'dot.gif';
    if ($zip->extractTo('.', $file) === TRUE) {
      echo "   $file extracted\n";
    } else {
      echo "   Failed to extract $file.\n";
    }

    mkdir('./tmp');
    if ($zip->extractTo('./tmp') === TRUE) {
      echo "   All files extracted\n";
    } else {
      echo "   Failed to extract all files.\n";
    }

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

Let's try it:

herong$ php zip-extract-file.php
Opening test.zip:
test.zip opened
dot.gif extracted
All files extracted

herong$ ls -l tmp
total 16
-rw-r--r--  1 herong  staff   43 Mar  1 15:37 dot.gif
-rw-r--r--  1 herong  staff  815 Mar  1 15:37 zip-create-new.php

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

 cURL Module - Client for URL

 DOM Module - Parsing HTML Documents

 GD Module - Manipulating Images and Pictures

 MySQLi Module - Accessing MySQL Server

 OpenSSL Module - Cryptography and SSL/TLS Toolkit

 PCRE Module - Perl Compatible Regular Expressions

 SOAP Module - Creating and Calling Web Services

 SOAP Module - Server Functions and Examples

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

 References

 Full Version in PDF/EPUB