ZIP archives
suggest changePHP provides comprehensive support for creating, reading, and extracting compressed ZIP files through the built-in ZipArchive class (part of the standard php-zip extension).
1. Creating a ZIP Archive
To create a new ZIP file, open it with the ZipArchive::CREATE flag. You can add files from the local filesystem using addFile() or create virtual files directly from memory using addFromString():
<?php
$zip = new ZipArchive();
$zipFilename = 'backup.zip';
// Open file with CREATE and OVERWRITE flags
$result = $zip->open($zipFilename, ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($result !== true) {
die("Failed to open archive for writing: Error code $result\n");
}
// 1. Add a file from disk with a custom internal name
$zip->addFile('/var/www/uploads/report.pdf', 'documents/2026_report.pdf');
// 2. Add content directly from a memory string
$zip->addFromString('manifest.json', json_encode([
'created_at' => date(DATE_ISO8601),
'author' => 'System Backup Worker',
'version' => '1.0'
], JSON_PRETTY_PRINT));
// 3. Create an empty directory entry
$zip->addEmptyDir('logs');
// Changes are only flushed to disk when close() is called
$zip->close();
echo "Successfully created $zipFilename\n";
2. Recursively Archiving a Folder
To archive an entire directory tree including subfolders, use RecursiveDirectoryIterator and RecursiveIteratorIterator:
<?php
function zipDirectory(string $sourceDir, string $outZipPath): bool
{
$sourceDir = realpath($sourceDir);
if (!$sourceDir || !is_dir($sourceDir)) {
return false;
}
$zip = new ZipArchive();
if ($zip->open($outZipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
return false;
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $file) {
// Skip directories (implied by file paths; empty directories are not archived)
if (!$file->isDir()) {
$filePath = $file->getRealPath();
// Calculate relative path inside the zip
$relativePath = substr($filePath, strlen($sourceDir) + 1);
// Normalize path separators to forward slash for cross-platform compatibility
$relativePath = str_replace('\\', '/', $relativePath);
$zip->addFile($filePath, $relativePath);
}
}
return $zip->close();
}
zipDirectory('/var/www/html/assets', '/tmp/assets.zip');
3. Extracting a ZIP Archive
Extracting an entire archive or specific entries is done with extractTo():
<?php
$zip = new ZipArchive();
if ($zip->open('archive.zip') === true) {
// Extract all files to destination directory
$zip->extractTo('/var/www/extracted/');
// Or extract only specific entries:
// $zip->extractTo('/var/www/extracted/', ['manifest.json', 'documents/2026_report.pdf']);
$zip->close();
echo "Archive extracted successfully.\n";
} else {
echo "Failed to open archive.\n";
}
Security Alert: Preventing "Zip Slip" Vulnerabilities
A malicious ZIP archive can contain entry names with relative directory traversals (such as ../../etc/passwd). Extracting such files without validation can overwrite critical system files.
Always validate target file destinations before extracting untrusted user-uploaded ZIPs:
<?php
function safeExtract(ZipArchive $zip, string $targetDir): void
{
$targetDir = realpath($targetDir);
for ($i = 0; $i < $zip->numFiles; $i++) {
$entryName = $zip->getNameIndex($i);
$name = str_replace('\\', '/', $entryName);
// Disallow directory traversal sequences, absolute paths and drive letters.
// (realpath() can't be used here: the destination folders don't exist yet)
if (str_contains($name, '..') || str_starts_with($name, '/') || preg_match('/^[a-zA-Z]:/', $name)) {
throw new RuntimeException("Zip Slip path traversal blocked: $entryName");
}
}
$zip->extractTo($targetDir);
}
4. Reading Files Without Extracting to Disk
You can read individual files directly from an archive in memory without extracting them to disk:
<?php
$zip = new ZipArchive();
if ($zip->open('archive.zip') === true) {
// Read file contents directly into a string
$manifestContent = $zip->getFromName('manifest.json');
if ($manifestContent !== false) {
$manifest = json_decode($manifestContent, true);
echo "Manifest version: " . $manifest['version'] . "\n";
}
// Iterate through archive entries and inspect metadata
for ($i = 0; $i < $zip->numFiles; $i++) {
$stat = $zip->statIndex($i);
printf(
"File: %s | Compressed: %d bytes | Uncompressed: %d bytes\n",
$stat['name'],
$stat['comp_size'],
$stat['size']
);
}
$zip->close();
}
Alternatively, use PHP's zip:// stream wrapper:
$content = file_get_contents('zip://archive.zip#manifest.json');
5. Password Encryption (AES-256)
Modern versions of ZipArchive support AES-128, AES-192, and AES-256 encryption:
<?php
$zip = new ZipArchive();
if ($zip->open('encrypted.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
// 1. Set archive default password
$zip->setPassword('StrongPassword123!');
// 2. Add entry
$zip->addFromString('confidential.txt', 'Highly confidential business data');
// 3. Set encryption method for the entry
$zip->setEncryptionName('confidential.txt', ZipArchive::EM_AES_256);
$zip->close();
}
To extract password-protected archives:
$zip = new ZipArchive();
if ($zip->open('encrypted.zip') === true) {
$zip->setPassword('StrongPassword123!');
$zip->extractTo('/tmp/decrypted/');
$zip->close();
}
Best Practices
- Always Check Return Values:
ZipArchive::open()returns booleantrueon success, or an integer error code (ZipArchive::ER_NOZIP,ZipArchive::ER_INCONS, etc.) on failure. - Normalize Directory Separators: Always convert Windows backslashes (
\) to standard forward slashes (/) for paths inside ZIP archives to ensure cross-platform compatibility on Linux and macOS. - Always Guard Against Zip Slip: Validate and sanitize entry names before extracting untrusted ZIP uploads.