Current Location: Home> Latest Articles> PHP ZipArchive Tutorial: Easily Handle Encoding and Decoding of ZIP Files

PHP ZipArchive Tutorial: Easily Handle Encoding and Decoding of ZIP Files

gitbox 2025-07-26

Introduction to PHP ZipArchive

PHP ZipArchive is a built-in PHP extension designed to work with ZIP archive files. It supports creating, opening, modifying, and extracting ZIP archives, making it a commonly used tool for handling compressed files.

This article focuses on how to implement encoding and decoding operations on ZIP files using PHP ZipArchive.

Encoding Operations on ZIP Files

Creating a ZIP Archive

You can create a new ZIP archive using the open method of the ZipArchive class, specifying the create mode. Example code:

$zip = new ZipArchive();
$zip->open('myarchive.zip', ZipArchive::CREATE);

This code creates a new ZIP archive named myarchive.zip.

Adding Files to the ZIP Archive

The addFile method allows adding files from the local system into the archive. Example:

$zip->addFile('file1.txt', 'file1.txt');
$zip->addFile('file2.txt', 'file2.txt');

This adds file1.txt and file2.txt into the archive, specifying their paths within the ZIP.

Setting a Password for the ZIP Archive

ZipArchive supports password protection through the setPassword method:

$zip->setPassword('password');

This example sets the ZIP archive password to password.

Decoding Operations on ZIP Files

Opening a ZIP Archive

Use the open method to open an existing ZIP archive:

$zip = new ZipArchive();
$zip->open('myarchive.zip');

This code opens the archive named myarchive.zip.

Extracting Files

The extractTo method extracts files from the archive to a specified directory:

$zip->extractTo('extracted_files');

This example extracts all files to the extracted_files directory.

Checking if the ZIP Archive is Encrypted

The checkPassword method checks whether the ZIP archive is password protected and if the provided password matches:

$isEncrypted = $zip->checkPassword('password');

This stores the result of the password check in the variable $isEncrypted.

Conclusion

This article demonstrated how to use PHP ZipArchive to encode and decode ZIP files, including creating archives, adding files, setting passwords, opening archives, extracting files, and checking encryption. ZipArchive is an efficient and user-friendly tool for managing ZIP files in PHP projects, suitable for most ZIP file operations.