How to zip a whole folder using PHP
When you need to archive a directory, standard file manipulation functions often fall short because they operate on single files rather than directory trees. The typical approach found in many tutorials involves iterating through files individually and adding them to a ZipArchive instance one by one. This method works for flat lists of files, but it becomes cumbersome when dealing with subdirectories or when you need to preserve the internal folder structure within the zip file itself.
To handle a whole folder efficiently, you must leverage the built-in capabilities of PHP's ZipArchive class, specifically its ability to add entire directories. The addDirectory() method is designed exactly for this purpose. It recursively scans the target path and includes all files and subdirectories relative to that root.
Consider a scenario where you have a folder named My Folder containing index.html, picture.jpg, and important.txt. If your goal is to create a zip file of this directory while simultaneously cleaning up the original location, you need to sequence your operations carefully. The most robust strategy is to initialize the ZipArchive, add the directory, close the archive, and then proceed with cleanup.
Here is how you might structure the logic in a script:
$zipFile = 'archive.zip';
$sourceDir = 'My Folder';
$keepFiles = ['important.txt']; // Files to preserve before deletion
// Create or open the zip file for writing
$zip = new ZipArchive();
if ($zip->open($zipFile, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) {
throw new RuntimeException('Unable to create zip file');
}
// Add the entire directory.
// Note: addDirectory includes the folder name in the path inside the zip.
$zip->addDirectory($sourceDir);
// Close the archive to ensure data is written to disk
$zip->close();
// At this point, the zip contains all files. Now handle cleanup.
// You must remove files that are NOT in your keep list.
foreach (glob("$sourceDir/*") as $file) {
$filename = basename($file);
// Skip if it matches a file we want to keep
if (in_array($filename, $keepFiles)) {
continue;
}
if (is_dir($file)) {
rmdir($file);
} else {
unlink($file);
}
}
There are significant trade-offs involved in combining archiving with cleanup logic. The primary risk is data loss during the process. If the zip writing fails partway through, you are left with a corrupted archive and a partially cleaned directory. To mitigate this, it is generally safer to perform the archival first, verify the integrity of the resulting zip file (perhaps by opening it in read-only mode), and only then execute the deletion logic.
Another technical nuance is how paths are stored inside the zip. When using addDirectory('My Folder'), the contents will be stored as /My Folder/index.html. If your downstream application expects a flat structure without the leading folder name, you may need to use addFile with specific path manipulation or change the working directory before adding files.
Additionally, consider the behavior of file permissions and timestamps. The standard ZipArchive implementation usually preserves these attributes from the source system. However, if you are deploying to an environment where you lack write permissions to the destination zip location, the operation will fail immediately upon opening the archive for creation. Always ensure the script runs with appropriate privileges or that the output path is writable by the executing user.
For developers working within the Laravel ecosystem, similar directory operations often require careful handling of public storage versus local filesystems. While ZipArchive works seamlessly on the local disk, archiving files stored in S3 or other cloud providers requires a different approach, typically involving downloading the files to a temporary location, zipping them, and then uploading the result.
Finally, be aware that addDirectory does not automatically handle hidden files or specific file extensions unless they are present in the directory tree. If your application logic relies on excluding certain types of files (like .env or cache dumps) from backups, you must filter them out manually before adding them to the archive.
