Приглашаем посетить
Биология (bio.niv.ru)

Using PHP Streams

Previous
Table of Contents
Next

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 Chapter 9, "Communicating with Others;" this chapter just picks out some file-specific features: compression streams.

Zipping and Unzipping a File (zip.php; excerpt)
<?php
  $filename = __FILE__;
  $zipfile = "$filename.zip";

  $data = file_get_contents(__FILE__);
  echo 'Loaded file (size: ' . strlen($data) .
    ').<br />';

  file_put_contents("compress.zlib://$zipfile",
    $data);
  echo 'Zipped file (new size: ' . filesize
    ($zipfile) . ').<br />';

  $data = file_get_contents("compress.zlib://
    $zipfile");
  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 http://zziplib.sourceforge.net/. 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 (zziplib.php)
<?php
  $zipfile = dirname(__FILE__) . '/archive.zip';
  if ($zip = zip_open($zipfile)) {
    while ($file = zip_read($zip)) {
      printf('%s (%d)<br />',
        zip_entry_name($file),
          zip_entry_filesize($file)
      );
    }
    zip_close($zip);
  }
?>


Previous
Table of Contents
Next