PHP Zip
Compressing and extracting ZIP archives in PHP
📦 What is PHP Zip?
PHP Zip extension allows you to create, read, and extract ZIP archive files. It's useful for compressing files, creating backups, and handling file downloads efficiently by bundling multiple files together.
<?php
// Create a new ZIP archive
$zip = new ZipArchive();
$zip->open('myarchive.zip', ZipArchive::CREATE);
$zip->addFile('document.txt');
$zip->close();
?>
Output:
ZIP archive 'myarchive.zip' created successfully
ZIP Operations Overview
Create Archives
Build new ZIP files
Extract Files
Unzip archive contents
Read Archives
List and inspect ZIP contents
Modify Archives
Update existing ZIP files
🔹 Creating a ZIP Archive
Create a new ZIP file and add files to it using the ZipArchive class. This is useful for bundling multiple files for download or backup purposes.
<?php
$zip = new ZipArchive();
$zipFile = 'myfiles.zip';
// Create new ZIP file
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
// Add files to ZIP
$zip->addFile('document.txt', 'document.txt');
$zip->addFile('image.jpg', 'images/image.jpg');
// Add string content as file
$zip->addFromString('readme.txt', 'This is a readme file');
$zip->close();
echo "ZIP archive created successfully!";
} else {
echo "Failed to create ZIP archive";
}
?>
Output:
ZIP archive created successfully!
🔹 Extracting ZIP Archives
Extract all files from a ZIP archive to a specified directory. You can extract the entire archive or specific files based on your needs.
<?php
$zip = new ZipArchive();
$zipFile = 'myfiles.zip';
// Open ZIP file
if ($zip->open($zipFile) === TRUE) {
// Extract to directory
$zip->extractTo('extracted_files/');
$zip->close();
echo "Files extracted successfully!";
} else {
echo "Failed to open ZIP archive";
}
// Extract specific file
$zip2 = new ZipArchive();
if ($zip2->open($zipFile) === TRUE) {
$zip2->extractTo('specific/', 'document.txt');
$zip2->close();
echo "<br>Specific file extracted!";
}
?>
Output:
Files extracted successfully!
Specific file extracted!
🔹 Listing ZIP Contents
Read and display information about files inside a ZIP archive without extracting them. This helps you inspect archive contents before extraction.
<?php
$zip = new ZipArchive();
$zipFile = 'myfiles.zip';
if ($zip->open($zipFile) === TRUE) {
echo "Number of files: " . $zip->numFiles . "<br><br>";
// List all files
for ($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = $zip->statIndex($i);
echo "File: " . $filename;
echo " (Size: " . $fileinfo['size'] . " bytes)<br>";
}
$zip->close();
} else {
echo "Failed to open ZIP archive";
}
?>
Output:
Number of files: 3
File: document.txt (Size: 1024 bytes)
File: images/image.jpg (Size: 45678 bytes)
File: readme.txt (Size: 25 bytes)
🔹 Adding Multiple Files
Add multiple files to a ZIP archive using loops or by scanning directories. This is efficient for backing up entire folders or creating bulk downloads.
<?php
$zip = new ZipArchive();
$zipFile = 'backup.zip';
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
// Array of files to add
$files = ['file1.txt', 'file2.txt', 'file3.txt'];
foreach ($files as $file) {
if (file_exists($file)) {
$zip->addFile($file, basename($file));
}
}
// Add entire directory
$dir = 'documents/';
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
$zip->addFile($dir . $file, 'docs/' . $file);
}
}
}
$zip->close();
echo "Multiple files added to ZIP!";
}
?>
Output:
Multiple files added to ZIP!
🔹 Deleting Files from ZIP
Remove specific files from an existing ZIP archive without recreating the entire archive. This is useful for updating archives by removing outdated files.
<?php
$zip = new ZipArchive();
$zipFile = 'myfiles.zip';
if ($zip->open($zipFile) === TRUE) {
// Delete a file by name
if ($zip->deleteName('readme.txt')) {
echo "File deleted from ZIP!<br>";
}
// Delete by index
if ($zip->deleteIndex(0)) {
echo "First file deleted!<br>";
}
$zip->close();
echo "ZIP archive updated!";
} else {
echo "Failed to open ZIP archive";
}
?>
Output:
File deleted from ZIP!
First file deleted!
ZIP archive updated!
🔹 Reading File Contents
Read the contents of files inside a ZIP archive without extracting them to disk. This is memory-efficient for processing archived data directly.
<?php
$zip = new ZipArchive();
$zipFile = 'myfiles.zip';
if ($zip->open($zipFile) === TRUE) {
// Read file content by name
$content = $zip->getFromName('readme.txt');
echo "Content: " . $content . "<br><br>";
// Read file by index
$content2 = $zip->getFromIndex(0);
echo "First file content: " . substr($content2, 0, 50) . "...";
$zip->close();
} else {
echo "Failed to open ZIP archive";
}
?>
Output:
Content: This is a readme file
First file content: This is the content of the first document in th...
🔹 Checking ZIP Status
Verify if a ZIP file exists and check for errors during operations. Proper error handling ensures your application handles archive operations gracefully.
<?php
$zip = new ZipArchive();
$zipFile = 'test.zip';
// Check if file exists
if (file_exists($zipFile)) {
echo "ZIP file exists!<br>";
} else {
echo "ZIP file not found!<br>";
}
// Try to open and check status
$status = $zip->open($zipFile);
if ($status === TRUE) {
echo "ZIP opened successfully!<br>";
echo "Number of files: " . $zip->numFiles;
$zip->close();
} else {
echo "Error opening ZIP. Error code: " . $status;
}
?>
Output:
ZIP file exists!
ZIP opened successfully!
Number of files: 5