PHP Zip

Beginner
8 min read
Updated: Nov 2026
3 examples
ZipArchive & legacy zip_*

Definition and Usage

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.

PHP also has a set of older procedural functions: zip_open(), zip_read(), zip_close(), and the zip_entry_* family such as zip_entry_name(), zip_entry_filesize() and zip_entry_read(). They can only read archives, and they are deprecated since PHP 8.0.

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)).

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);

Core Ideas

What to remember when you work with ZIP files, and how the legacy functions map to ZipArchive:

IdeaZipArchiveLegacy functionRemember
Open or createopen($path, $flags)zip_open()Use ZipArchive::CREATE to make a new file and ZipArchive::OVERWRITE to replace one; the legacy function can only open an existing archive
Closeclose()zip_close()For writing, the archive is saved when you call close(), so never skip it
Walk the entriesnumFiles + statIndex()zip_read()A for loop over the index replaces the read-next-entry style
Entry namegetNameIndex($i)zip_entry_name()Names use forward slashes; a folder entry ends with /
Entry sizestatIndex($i)['size']zip_entry_filesize() / zip_entry_compressedsize()The array also has comp_size and comp_method, the same data that zip_entry_compressionmethod() returns
Read contentgetFromName() / getFromIndex()zip_entry_open() + zip_entry_read() + zip_entry_close()One method call gives the whole file as a string; it returns false when the entry is missing
ExtractextractTo($dir)None (read each entry yourself)Pass a second argument to extract only some entries
Add contentaddFromString() / addFile()NoneWriting 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.

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:

PHP
var_dump(extension_loaded('zip'));     // bool
var_dump(class_exists('ZipArchive'));  // bool
PlatformWhat to do
Linux (Debian, Ubuntu)Install the package for your PHP version, for example php-zip, then restart PHP-FPM or Apache
WindowsOpen php.ini, remove the semicolon before extension=zip, and restart the web server
Custom PHP buildConfigure PHP with --with-zip and rebuild

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);
?>

How It Works

  1. sys_get_temp_dir() gives a folder PHP can always write to, so the script does not depend on your project layout.
  2. 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.
  3. 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.
  4. close() writes the archive to disk. Without it the file would not exist yet.
  5. 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.

PHP
<?php
$path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'codetofun_demo2.zip';

$zip = new ZipArchive();
$zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip->addFromString('a.txt', 'Alpha');
$zip->addFromString('docs/b.txt', 'Bravo!');
$zip->addFromString('docs/c.txt', 'Charlie');
$zip->close();

$zip = new ZipArchive();
if ($zip->open($path) === true) {
    echo 'Entries: ', $zip->numFiles, PHP_EOL;

    for ($i = 0; $i < $zip->numFiles; $i++) {
        $st = $zip->statIndex($i);
        echo $i, ': ', $st['name'], ' (', $st['size'], ' bytes)', PHP_EOL;
    }

    echo 'Name at index 1: ', $zip->getNameIndex(1), PHP_EOL;
    $zip->close();
}

unlink($path);
?>

How It Works

  1. Entries are numbered from 0 in the order they were added, so the first addFromString() call becomes index 0.
  2. numFiles is a property, not a method, and holds the number of entries. It is the upper limit for the loop.
  3. 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.
  4. getNameIndex(1) is the shortcut when you only need the name. Both methods return false for an index that does not exist.
  5. 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.

PHP
<?php
$path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'codetofun_demo3.zip';

$zip = new ZipArchive();
$zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip->addFromString('config.ini', "mode=demo\nlevel=3");
$zip->close();

$zip = new ZipArchive();
if ($zip->open($path) === true) {
    $text = $zip->getFromName('config.ini');

    echo $text, PHP_EOL;
    echo 'Length: ', strlen($text), PHP_EOL;
    echo 'Index of config.ini: ', $zip->locateName('config.ini'), PHP_EOL;
    echo 'Missing file: ', var_export($zip->getFromName('nope.txt'), true), PHP_EOL;

    $zip->close();
}

unlink($path);
?>

How It Works

  1. The string "mode=demo\nlevel=3" uses double quotes, so \n becomes a real line break. That is why the output shows two lines.
  2. 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.
  3. The length is 17: mode=demo is 9 bytes, the line break is 1, and level=3 is 7.
  4. locateName() returns the index of an entry, here 0, or false when the name is not found.
  5. 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.

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.

Legacy functionWhat it does
zip_open()Open a ZIP file for reading and get a handle
zip_read()Move to the next entry in the archive
zip_close()Close the archive handle
zip_entry_open()Open an entry so its data can be read
zip_entry_read()Read bytes from an open entry
zip_entry_close()Close an entry that was opened
zip_entry_name()Get the name of an entry
zip_entry_filesize()Get the original size of an entry
zip_entry_compressedsize()Get the compressed size of an entry
zip_entry_compressionmethod()Get the compression method used for an entry

Full list: PHP Zip Functions index (/php/zip/function).

Frequently Asked Questions

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.

Browse every Zip function

Open the functions index for the legacy zip_* guides with examples and FAQs.

Zip Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful