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, uncomment extension=zip in php.ini. On Linux, install with sudo 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() returns TRUE
  • Use ZipArchive::CREATE flag to create new zip files
  • Remember to call close() to finalize the zip file
  • Use RecursiveDirectoryIterator for 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.

Updated on: 2026-03-15T08:14:43+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements