PHP Tutorials - Herong's Tutorial Examples - v5.16, by Herong Yang
Exact 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
Introduction and Installation of PHP 7.3
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
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
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
Create ZIP Archive with Directory
Create ZIP Archive for Download
Managing PHP Engine and Modules on macOS