Google’s results for code snippets to create a .zip archive with PHP gives quite a few results. However, none of the code examples can recursively compress a directory and replicate the same structure in the .zip archive. One code snippet from the PHP Manual’s reference page for Zip functions comes pretty close, but the RecursiveDirectoryIterator never worked for me. The code always failed with an error about excessive recursion, with the script reaching the limit of 100 recursion levels.

Thankfully, after some more searching, I tried another code snippet from the same page, written by nheimann {at} gmx {dot} net.  With a little tweaking, the code worked perfectly. The class in the code snippet extends the ZipArchive class, and adds an addDir() public method. Example usage of this class is:

The class in the PHP Manual’s reference had a few missing variables. The correct code for the class is: