The PHP Zip extension lets a script create, read, and unpack ZIP archives. The modern way to do this is the ZipArchive class. You make an object, open an archive with open(), add or read entries, and finish with close(). The same class can build a new archive, change an existing one, and extract it.
This page teaches the ideas with ZipArchive. The Zip Functions index has a guide for each legacy function, so you can still understand old code when you meet it.
Use ZipArchive for new code.
It is the maintained API, it can write archives, and every procedural function has a matching method. Learn the zip_* functions only to read or migrate legacy code.
Always check what open() returns.
ZipArchive::open() returns true on success, but on failure it returns an error code, which is a non-zero integer and therefore truthy. Write if ($zip->open($path) === true), never just if ($zip->open($path)).
Syntax
PHP Syntax
The usual pattern with ZipArchive: open, work with entries, close:
PHP
$zip = new ZipArchive();
// true on success, an int error code on failure
$result = $zip->open('files.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($result === true) {
$zip->addFromString('hello.txt', 'Hello, Zip!'); // bool: add text as a file
$zip->addFile('/path/to/photo.jpg', 'photo.jpg'); // bool: add a file from disk
echo $zip->numFiles; // int: number of entries
$info = $zip->statIndex(0); // array: name, size, comp_size, mtime ...
echo $zip->getNameIndex(0); // string: entry name, false if missing
echo $zip->getFromName('hello.txt'); // string: content, false if missing
$zip->extractTo('/path/to/folder'); // bool: unpack every entry
$zip->close(); // bool: write changes and release the file
}
// Legacy (deprecated since PHP 8.0): read-only, procedural
// $z = zip_open('files.zip');
// while ($entry = zip_read($z)) { echo zip_entry_name($entry); }
// zip_close($z);
Reference
Core Ideas
What to remember when you work with ZIP files, and how the legacy functions map to ZipArchive:
One method call gives the whole file as a string; it returns false when the entry is missing
Extract
extractTo($dir)
None (read each entry yourself)
Pass a second argument to extract only some entries
Add content
addFromString() / addFile()
None
Writing is only possible with ZipArchive
Be careful when you extract.
Archives from other people can hold names such as ../../file.php. extractTo() guards against the worst cases, but you should still extract untrusted archives into an empty folder that you control, and check the entry names first.
Setup
Enabling the Zip Extension
The zip extension is common but may need enabling. If you see Class "ZipArchive" not found, or the zip_* functions are undefined, the extension is not loaded. Check it first:
Install the package for your PHP version, for example php-zip, then restart PHP-FPM or Apache
Windows
Open php.ini, remove the semicolon before extension=zip, and restart the web server
Custom PHP build
Configure PHP with --with-zip and rebuild
Code
PHP Examples
Three short scripts that show how ZipArchive works. Each one builds its own archive inside sys_get_temp_dir() and deletes it at the end, so the output is the same every time you run it.
Example 1 — Create an archive and extract it
Build a ZIP with addFromString(), reopen it, unpack it with extractTo(), and print what came out.
PHP
<?php
$tmp = sys_get_temp_dir();
$path = $tmp . DIRECTORY_SEPARATOR . 'codetofun_demo1.zip';
$dir = $tmp . DIRECTORY_SEPARATOR . 'codetofun_demo1_out';
// 1) Create the archive
$zip = new ZipArchive();
if ($zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
exit('Cannot create the archive');
}
$zip->addFromString('hello.txt', 'Hello, Zip!');
$zip->addFromString('docs/readme.txt', 'Read me first.');
$zip->close();
echo 'Created: ', basename($path), PHP_EOL;
// 2) Reopen it and extract
$zip = new ZipArchive();
if ($zip->open($path) === true) {
$zip->extractTo($dir);
$zip->close();
}
echo 'hello.txt: ', file_get_contents($dir . '/hello.txt'), PHP_EOL;
echo 'docs/readme.txt: ', file_get_contents($dir . '/docs/readme.txt'), PHP_EOL;
// Clean up
unlink($dir . '/hello.txt');
unlink($dir . '/docs/readme.txt');
rmdir($dir . '/docs');
rmdir($dir);
unlink($path);
?>
Created: codetofun_demo1.zip
hello.txt: Hello, Zip!
docs/readme.txt: Read me first.
How It Works
sys_get_temp_dir() gives a folder PHP can always write to, so the script does not depend on your project layout.
open() with CREATE | OVERWRITE makes a new archive, or replaces an old one. The !== true check handles the error code that open() returns on failure.
addFromString() stores text as a file inside the archive. The name docs/readme.txt makes a docs folder in the archive without any extra call.
close() writes the archive to disk. Without it the file would not exist yet.
extractTo($dir) creates the folder if needed and unpacks every entry into it, keeping the folder structure. The script then reads the files back and removes everything it created.
Example 2 — List entries with numFiles, statIndex() and getNameIndex()
Create a three-file archive, then walk it by index and print each name with its size.
Entries: 3
0: a.txt (5 bytes)
1: docs/b.txt (6 bytes)
2: docs/c.txt (7 bytes)
Name at index 1: docs/b.txt
How It Works
Entries are numbered from 0 in the order they were added, so the first addFromString() call becomes index 0.
numFiles is a property, not a method, and holds the number of entries. It is the upper limit for the loop.
statIndex($i) returns an array. This script uses the name and size keys; it also has comp_size, mtime, crc and comp_method. Alpha, Bravo! and Charlie are 5, 6 and 7 bytes long.
getNameIndex(1) is the shortcut when you only need the name. Both methods return false for an index that does not exist.
This for loop does the job of the old zip_read() loop, with the extra benefit that you can jump to any entry directly.
Example 3 — Read one file with getFromName()
Read a file straight out of the archive without extracting it, and see what a missing name returns.
mode=demo
level=3
Length: 17
Index of config.ini: 0
Missing file: false
How It Works
The string "mode=demo\nlevel=3" uses double quotes, so \n becomes a real line break. That is why the output shows two lines.
getFromName('config.ini') opens the entry, reads it completely, and returns the content as a string. This replaces the three-step zip_entry_open(), zip_entry_read(), zip_entry_close() routine.
The length is 17: mode=demo is 9 bytes, the line break is 1, and level=3 is 7.
locateName() returns the index of an entry, here 0, or false when the name is not found.
A name that is not in the archive makes getFromName() return false, shown here with var_export(). In real code, compare with === false because an empty file returns an empty string, which is also falsy.
Continue
Next: PHP Zip Functions Index
After you know ZipArchive, open the functions index to read about the deprecated procedural functions you may find in older code. Each one links to its own guide.
Use the ZipArchive class from the zip extension. It can create archives, add files and strings, list entries, read single files, and extract everything with extractTo(). It is the maintained API, and it is the only one that can write archives. The older procedural functions such as zip_open() and zip_read() can only read and are deprecated since PHP 8.0.
They are deprecated since PHP 8.0, not removed. They still work and raise a deprecation notice, but new code should not use them. You will mostly meet them in older tutorials and legacy projects. Each procedural function has a ZipArchive method that does the same job, so moving over is straightforward.
Open the archive with ZipArchive::open(), then call getFromName('path/in/archive.txt') to get the content as a string, or getFromIndex($i) when you know the position. Both return false if the entry does not exist, so compare with === false before you use the result.
After open() succeeds, loop from 0 to numFiles - 1. For each index call getNameIndex($i) to get the name only, or statIndex($i) to get an array with name, size, compressed size, modification time and CRC. Folder entries end with a slash.
The zip extension is not enabled in your PHP build. Check it with class_exists('ZipArchive') or extension_loaded('zip'). On Linux install the package for your PHP version (often php-zip) and restart PHP. On Windows remove the semicolon before extension=zip in php.ini and restart the web server.
On success it returns true. On failure it returns an error code as an integer, for example ZipArchive::ER_NOENT when the file does not exist or ZipArchive::ER_NOZIP when it is not a ZIP file. Because the error is a non-zero integer, always test with $zip->open($path) === true and never with a plain if.