Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to Zip a directory in PHP?
We can use PHP's ZipArchive class to zip and unzip directories in PHP. As of PHP 5.3, this class is built-in. Windows users need to enable php_zip.dll in their php.ini file.
Installation Note: Ensure the PHP Zip extension is enabled. On Windows, uncommentextension=zipin php.ini. On Linux, install withsudo apt-get install php-zip.
Basic Directory Zipping
Here's how to zip all files in a directory −
<?php
// Enter the name of directory
$pathdir = "Directory Name/";
// Enter the name to creating zipped directory
$zipcreated = "test.zip";
// Create new zip class
$newzip = new ZipArchive;
if($newzip->open($zipcreated, ZipArchive::CREATE) === TRUE) {
$dir = opendir($pathdir);
while($file = readdir($dir)) {
if(is_file($pathdir.$file)) {
$newzip->addFile($pathdir.$file, $file);
}
}
closedir($dir);
$newzip->close();
echo "Directory zipped successfully!";
} else {
echo "Failed to create zip file";
}
?>
Recursive Directory Zipping
To zip directories with subdirectories, use this recursive function −
<?php
function zipDirectory($source, $destination) {
$zip = new ZipArchive();
if ($zip->open($destination, ZipArchive::CREATE) !== TRUE) {
return false;
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if ($file->isDir()) {
$zip->addEmptyDir(str_replace($source, '', $file));
} else {
$zip->addFile($file, str_replace($source, '', $file));
}
}
$zip->close();
return true;
}
// Usage
$sourceDir = 'path/to/source/directory/';
$zipFile = 'archive.zip';
if (zipDirectory($sourceDir, $zipFile)) {
echo "Directory archived successfully!";
} else {
echo "Failed to create archive";
}
?>
Key Points
- Always check if
ZipArchive::open()returnsTRUE - Use
ZipArchive::CREATEflag to create new zip files - Remember to call
close()to finalize the zip file - Use
RecursiveDirectoryIteratorfor subdirectories
Conclusion
PHP's ZipArchive class provides an efficient way to compress directories. Use the basic method for simple directories or the recursive approach for complex folder structures with subdirectories.
Advertisements
