How to recursively Zip a directory in PHP?

Recursively Zipping a Directory in PHP

Zipping a directory recursively in PHP is a practical task for developers who need to archive files and folders efficiently. Whether you're preparing backups, deploying applications, or sharing project files, understanding how to automate the zipping process can save you time and streamline your workflow.

Using Recursive Functions with PHP's ZipArchive

PHP provides the ZipArchive class, which allows you to create and manage ZIP files. To zip a directory recursively, you'll need to traverse through all subdirectories and add each file to the archive. Here's a step-by-step guide to accomplish this:

Step 1: Initialize ZipArchive

First, create a new instance of the ZipArchive class and open a new ZIP file for writing.

<?php $zip = new ZipArchive(); $zipFileName = 'archive.zip'; if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) { exit("Cannot open <$zipFileName>\n"); } ?>

Step 2: Create a Recursive Function to Add Files

Define a function that takes the directory path and the ZipArchive instance as parameters. This function will iterate through each file and subdirectory, adding them to the ZIP archive.

<?php function addFilesToZip($folder, &$zip, $parentFolder = '') { $handle = opendir($folder); if (!$handle) { return false; } while (($file = readdir($handle)) !== false) { if ($file == '.' || $file == '..') { continue; } $filePath = $folder . DIRECTORY_SEPARATOR . $file; $localPath = $parentFolder . $file; if (is_dir($filePath)) { // Add directory to zip $zip->addEmptyDir($localPath); // Recurse into subdirectory addFilesToZip($filePath, $zip, $localPath . '/'); } else { // Add file to zip $zip->addFile($filePath, $localPath); } } closedir($handle); return true; } ?>

Step 3: Execute the Function and Close the Archive

Call the recursive function with the target directory and close the ZIP archive once all files are added.

<?php $directoryToZip = 'path/to/your/directory'; if (addFilesToZip($directoryToZip, $zip)) { echo "Directory zipped successfully."; } else { echo "Failed to zip the directory."; } $zip->close(); ?>

Complete Example

Putting it all together, here's the complete PHP script to recursively zip a directory:

<?php function addFilesToZip($folder, &$zip, $parentFolder = '') { $handle = opendir($folder); if (!$handle) { return false; } while (($file = readdir($handle)) !== false) { if ($file == '.' || $file == '..') { continue; } $filePath = $folder . DIRECTORY_SEPARATOR . $file; $localPath = $parentFolder . $file; if (is_dir($filePath)) { $zip->addEmptyDir($localPath); addFilesToZip($filePath, $zip, $localPath . '/'); } else { $zip->addFile($filePath, $localPath); } } closedir($handle); return true; } $zip = new ZipArchive(); $zipFileName = 'archive.zip'; if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) { exit("Cannot open <$zipFileName>\n"); } $directoryToZip = 'path/to/your/directory'; if (addFilesToZip($directoryToZip, $zip)) { echo "Directory zipped successfully."; } else { echo "Failed to zip the directory."; } $zip->close(); ?>

Considerations

  • Permissions: Ensure that the PHP script has the necessary permissions to read the directories and files you intend to zip.
  • Error Handling: Enhance the script with more robust error handling to manage scenarios where files cannot be accessed or added to the archive.
  • Performance: For very large directories, consider optimizing the script to handle memory usage and execution time efficiently.

Learn More with DesignGurus.io

To further enhance your PHP skills and master file system operations, explore these courses:

Additionally, check out the Complete System Design Guide for comprehensive insights into organizing and structuring data efficiently.

Happy coding!

TAGS
Coding Interview
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Which software is used for MongoDB?
What is PCB in OS?
What is the highest paid software engineer salary?
What is special about Amazon?
What is the Google rule of 4?
What is recursion and when should I use it?
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
Discounted price for Your Region

$72

Grokking Data Structures & Algorithms for Coding Interviews course cover
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
Discounted price for Your Region

$78

Design Gurus logo
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.