Introduction to Working with ZIP Archives in PHP
Creating and processing ZIP archives is a common task in web development. In PHP, this task is solved using the built-in Zip extension, which provides a powerful and convenient ZipArchive class. With it, you can create new archives, extract existing ones, add or delete files, and work with metadata.
In this article, we will thoroughly cover all the main operations with ZIP archives in PHP: from simple creation to error handling and working with passwords. All examples are ready to use in your projects.
Preparation: Checking the Zip Extension
Before you start, make sure the zip extension is installed and enabled on your server. You can check this using the phpinfo() function or a simple script:
<?phpif (extension_loaded('zip')) { echo "Zip extension is available";} else { echo "Zip extension not found";}?>If the extension is missing, install it via your OS package manager (e.g., apt install php-zip for Ubuntu) or enable it in the php.ini file.
Creating a New ZIP Archive
The simplest way to create an archive is to open a new file in write mode and add files to it. Let's look at a basic example:
<?php$zip = new ZipArchive();$filename = 'example.zip';
// Create a new archive (ZIPARCHIVE::CREATE)if ($zip->open($filename, ZipArchive::CREATE) === TRUE) { // Add a file from the local file system $zip->addFile('/path/to/file1.txt', 'file1.txt'); // Add a string as a new file in the archive $zip->addFromString('hello.txt', 'Hello, world!'); // Add an entire folder (recursively) $zip->addGlob('/path/to/dir/*.*'); $zip->close(); echo "Archive $filename created successfully";} else { echo "Error creating archive";}?>Note: the second parameter of addFile() is the file name inside the archive. If not specified, the file will be saved with its original name.
Extracting a ZIP Archive
Extracting files from an archive is done using the extractTo() method. Specify the target folder where the files will be extracted:
<?php$zip = new ZipArchive();if ($zip->open('example.zip') === TRUE) { // Extract everything to the 'unpacked' folder $zip->extractTo('/path/to/unpacked/'); $zip->close(); echo "Archive extracted";} else { echo "Error opening archive";}?>If you need to extract only specific files, pass their list as the third argument:
$zip->extractTo('/path/to/unpacked/', ['file1.txt', 'hello.txt']);Viewing Archive Contents
Sometimes you need to get a list of files inside an archive without extracting it. Use the properties and methods of ZipArchive:
<?php$zip = new ZipArchive();if ($zip->open('example.zip') === TRUE) { echo "Number of files: " . $zip->numFiles . "<br>"; for ($i = 0; $i < $zip->numFiles; $i++) { $stat = $zip->statIndex($i); echo "File: " . $stat['name'] . " (size: " . $stat['size'] . " bytes)<br>"; } $zip->close();}?>Adding Files While Preserving Folder Structure
To preserve the directory hierarchy when adding files, use relative paths in the file name inside the archive:
<?php$zip = new ZipArchive();$zip->open('backup.zip', ZipArchive::CREATE);
// Add a file while preserving the subfolder$zip->addFile('/var/www/images/photo.jpg', 'images/photo.jpg');// Or recursively add an entire folder$zip->addPattern('/\\.(jpg|png)$/', '/var/www/images/', ['add_path' => 'images/']);
$zip->close();?>Deleting Files from an Archive
To delete a specific
Also in library
Cryptography in C++: Encryption and Hashing with OpenSSL and Crypto++
OAuth Client for Java: Overview of Libraries and Code Examples
wiremock-rs for Rust: Complete Guide with Examples
Processing Markdown in TypeScript: Libraries, Parsers, and Practical Applications
OneOf for C# (.NET): Complete Guide with Examples