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.
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.
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.
ZipArchive supports password protection through the setPassword method:
$zip->setPassword('password');
This example sets the ZIP archive password to password.
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.
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.
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.
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.