aboutsummaryrefslogtreecommitdiff
path: root/content/posts/2007-09-22-streaming-zip-files-with-php.html
blob: 3a7029565c7ff5551ee2315e978dbfe43233bdbf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
---
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-&gt;add_file('some_file.gif', $data);

# add second file
$data = file_get_contents('another_file.txt');
$zip-&gt;add_file('another_file.txt', $data);

# finally, finish the stream
$zip-&gt;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-&gt;add_file('foo.txt', $data, array(
  'comment' =&gt; 'this is an interesting comment',
  'time'    =&gt; 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>