php_ref_zip
PHP Zip Functions (ZipArchive Class)
Section titled “PHP Zip Functions (ZipArchive Class)”PHP Zip Extension Introduction
Section titled “PHP Zip Extension Introduction”PHP’s Zip extension allows you to create, read, and modify ZIP archives directly within your scripts. The primary way to interact with ZIP files is through the object-oriented ZipArchive class.
Installation / Enabling the Extension
Section titled “Installation / Enabling the Extension”The Zip extension is commonly included but may not be enabled by default in all PHP installations.
- Linux Systems (using package managers): Often installed via a package like
php-zip(Debian/Ubuntu) orphp-pecl-zip(CentOS/RHEL). Example:sudo apt-get install php-ziporsudo yum install php-pecl-zip. You might need to restart your web server (Apache/Nginx) and PHP-FPM afterwards. - Windows Systems: The
php_zip.dllfile should be included with your PHP distribution. You need to enable it in yourphp.inifile by uncommenting or adding the line:extension=zip. Ensure theextension_dirdirective inphp.inipoints to the directory containing the DLL file. Restart your web server. - Docker: Official PHP Docker images often require installing the extension within the Dockerfile. Example instructions can usually be found on the Docker Hub page for the PHP image.
- Checking: You can verify if the extension is enabled by running
php -min your terminal or by looking for a ‘zip’ section in the output ofphpinfo();.
Consult your specific operating system or hosting environment documentation for the precise steps.
Using the ZipArchive Class
Section titled “Using the ZipArchive Class”The ZipArchive class provides methods for working with ZIP files.
Common Workflow:
- Create a
ZipArchiveobject:$zip = new ZipArchive(); - Open an existing ZIP file or create a new one:
$zip->open('myarchive.zip', ZipArchive::CREATE); - Perform operations: Add files (
addFile()), add directories (addEmptyDir()), extract files (extractTo()), get information (numFiles,statIndex()), etc. - Close the archive to save changes:
$zip->close();
Example: Creating a Zip Archive
Section titled “Example: Creating a Zip Archive”<?php$zip = new ZipArchive();$filename = "./my_new_archive.zip";
// Open the archive for creation or overwriteif ($zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) { // Add a file using its path // Second parameter is the name it will have inside the archive if (file_exists('file1.txt')) { $zip->addFile('file1.txt', 'document.txt'); }
// Add a file from a string $zip->addFromString('generated.txt', 'This content was generated on the fly.');
// Add an empty directory $zip->addEmptyDir('new_folder');
// Add all files from a directory (recursive example) $sourceDir = './files_to_zip'; // Directory containing files if (is_dir($sourceDir)) { $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY );
foreach ($files as $name => $file) { // Skip directories (they would be added automatically) if (!$file->isDir()) { $filePath = $file->getRealPath(); // Get relative path to store correctly in zip $relativePath = substr($filePath, strlen($sourceDir) + 1); $zip->addFile($filePath, $relativePath); } } }
// Close and save the archive $zip->close(); echo 'Archive created successfully.';} else { echo 'Failed to create the archive.';}?>Example: Extracting a Zip Archive
Section titled “Example: Extracting a Zip Archive”<?php$zip = new ZipArchive();$filename = "./my_new_archive.zip";$extractToPath = "./extracted_files";
// Open the archive for readingif ($zip->open($filename) === TRUE) { // Create extraction directory if it doesn't exist if (!is_dir($extractToPath)) { mkdir($extractToPath, 0755, true); }
// Extract all contents to the specified path if ($zip->extractTo($extractToPath)) { echo 'Archive extracted successfully.'; } else { echo 'Failed to extract archive.'; }
// Close the archive $zip->close();} else { echo 'Failed to open the archive.';}?>Example: Reading File List from Archive
Section titled “Example: Reading File List from Archive”<?php$zip = new ZipArchive();$filename = "./my_new_archive.zip";
if ($zip->open($filename) === TRUE) { echo "Archive '{$filename}' contains: " . $zip->numFiles . " files/directories.\n"; echo "-------------------------------------\n";
for ($i = 0; $i < $zip->numFiles; $i++) { $stats = $zip->statIndex($i); if (!$stats) continue;
echo "Name: " . $stats['name'] . "\n"; echo "Size (uncompressed): " . $stats['size'] . " bytes\n"; echo "Size (compressed): " . $stats['comp_size'] . " bytes\n"; echo "-------------------------------------\n"; }
$zip->close();} else { echo 'Failed to open the archive.';}?>Key ZipArchive Methods
Section titled “Key ZipArchive Methods”Here are some commonly used methods:
For a complete list and detailed descriptions, consult the official PHP ZipArchive documentation.