PHP Zip
Zip archives are files that are compressed using the zip compression algorithm. They are often used to reduce the size of files and make them easier to transfer over the internet or store on disk. A zip archive can contain one or more files, and it typically has a .zip file extension.
PHP ZipArchive Class
The legacy zip_* functions were deprecated in PHP 7.4 and removed in PHP 8.0. Modern PHP applications should use the built-in ZipArchive class, which provides a robust object-oriented interface for creating, reading, and extracting ZIP archives.
Key methods include:
open()– Opens a ZIP archive for reading or writing.extractTo()– Extracts all files or specific entries to a specified directory.close()– Closes the archive handle.getStatusString()– Returns a human-readable status message for error handling.
Example Usage
The following example demonstrates how to use ZipArchive to extract the contents of a ZIP file to disk, including basic error handling:
$zip = new ZipArchive();
$filename = 'example.zip';
$extractTo = './extracted_files';
if ($zip->open($filename) === true) {
if (!is_dir($extractTo)) {
mkdir($extractTo, 0755, true);
}
if ($zip->extractTo($extractTo) === true) {
echo "Archive extracted successfully.";
} else {
echo "Extraction failed: " . $zip->getStatusString();
}
$zip->close();
} else {
echo "Failed to open archive.";
}In this example, we instantiate the ZipArchive class and attempt to open the archive using open(). If successful, we ensure the target directory exists, then extract all contents using extractTo(). We check the return value and use getStatusString() for error reporting before closing the handle with close().
Conclusion
In this article, we've discussed how to work with ZIP archives in modern PHP using the ZipArchive class. We've explained what ZIP archives are and provided a practical example of how to extract files to disk with proper error handling. By using ZipArchive in your PHP applications, you can reliably manage compressed files for transfer or storage.
Practice
Which of the following statements is/are true about the ZIP extension in PHP?