--- date: "2007-09-22T05:40:41Z" title: Streaming Zip Files with PHP --- <p>The problem: how do you dynamically generate arbitrarily large downloadable zip files from PHP? All of the existing solutions I found all generate a local temp file, which means the server needs to </p> <ul> <li>have a web-writable directory large enough to store the intermediate temp file, and</li> <li>be able to generate and start streaming the entire file before the client times out </li> </ul> <p>I wasn't particularly fond of either constraint, so I came up with a solution: <a href="http://pablotron.org/software/zipstream-php/" title="ZipStream-PHP project page.">ZipStream-PHP</a>. ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server. Using it is dirt simple, too. Here's how:</p> <pre><code># create a new stream object $zip = new ZipStream('example.zip'); # then add one or more files # add first file $data = file_get_contents('some_file.gif'); $zip->add_file('some_file.gif', $data); # add second file $data = file_get_contents('another_file.txt'); $zip->add_file('another_file.txt', $data); # finally, finish the stream $zip->finish(); </code></pre> <p>You can also set file comments and creation dates, like so:</p> <pre><code>$data = file_get_contents('foo.txt'); $zip->add_file('foo.txt', $data, array( 'comment' => 'this is an interesting comment', 'time' => time() - 3600, # created one hour ago )); </code></pre> <p>Here are the links, enjoy:</p> <ul> <li><a href="http://pablotron.org/files/zipstream-php-0.1.1.tar.gz" title="ZipStream-PHP 0.1.1 tarball.">Download ZipStream-PHP 0.1.1</a> (<a href="http://pablotron.org/files/zipstream-php-0.1.1.tar.gz.asc" title="PGP signature for ZipStream-PHP 0.1.1 tarball.">Signature</a>)</li> <li><a href="http://hg.pablotron.org/zipstream-php/" title="ZipStream-PHP Mercurial repository.">ZipStream Mercurial Repository</a></li> </ul>