Using PHP Streams

In PHP, the concept of PHP streams was introduced. Since then, there is a common denominator for all kinds of resources: files, HTTP and FTP data, and even archive file formats. More about the networking aspect of this can be found in greater detail in Connecting With HTTP Servers, "Communicating with Others;" this chapter just picks out some file-specific features: compression streams.

Zipping and Unzipping a File

  $filename = __FILE__;
  $zipfile = "$";
  $data = file_get_contents(__FILE__);
  echo 'Loaded file (size: ' . strlen($data) .
    ').<br />';
  echo 'Zipped file (new size: ' . filesize
    ($zipfile) . ').<br />';
  $data = file_get_contents("compress.zlib://
  echo 'Original file size: ' . strlen($data) .

One of them can be used to use ZIP files. The pseudo protocol compress.zlib:// can be used to access ZIP files as you would access regular files. For this to work, you have to use the configuration switch with-gzip under UNIX/Linux; Windows systems have the required libraries already included. Then, you can use the files using, for instance, file_get_contents() and file_put_contents().

The preceding code loads the current file (with file_get_contents()), zips it, and writes it to the hard disk (with file_put_contents()). Then, it reads in the zipped file (with file_get_contents()) and compares the file sizes.

When testing this, the code managed to compress the file from 729 to 336 bytes.

Alternatively, you can use PHP's built-in ZIP functions, which are implemented by a wrapper to the ZZIPlib library from This one can only read data from a ZIP file, unfortunately, but also supports multiple files within an archive (when using the stream wrapper compress.zlib://, you first have to tar data to support multiple files).

To install, use extension=php_zip.dll in php.ini under Windows, or configure PHP with with-zip, providing the path to ZZIPlib. The following steps must be taken to use this extension:

  • Open the archive using zip_open()

  • Iterate through the archive's entries with zip_read()

  • Read a specific file using zip_entry_open() and zip_entry_read()

The following code shows the contents of a ZIP archive and determines the names and file size of all entries.

Unzipping a File Using ZZIPlib

  $zipfile = dirname(__FILE__) . '/';
  if ($zip = zip_open($zipfile)) {
    while ($file = zip_read($zip)) {
      printf('%s (%d)<br />',

by BrainBellupdated