CHAPTER 9 – FILES AND STREAMS – Compression Streams

PHP provides some wrappers around compression functions. Previously, you needed specialized functions for accessing gzip and bzip compressed files; you can now use the streaming support for those libraries. Reading from and writ- ing to a gzipped or bzipped file works exactly the same as reading and writing a normal file. To use the compression methods, you need to compile PHP with --with-zlib to provide the compress.zlib:// wrapper and --with-bz2 to provide the compress.bzip2:// wrapper. Of course, you need to have the zlib and/or bzip2 libraries installed before you can enable those extensions.

Gzip streams support more mode specifiers then the standard r, w, a, b, and +. These additional modifiers include the compression level 1-9 and the compres- sion methods f for filtered and h for huffman only compressing. These modifiers only make sense if you open the file for writing. In the following example, we demonstrate copying a file from a bzipped file to a gzipped file. We make use of the compression level specifier 1 to speed up compression, and the third parameter fopen(), to specify searching for the file in the include path. Be careful when using the include path parameter because it will have a performance impact on your script. PHP tries to find and open the file throughout the entire include path, which slows down your script because file operations are generally show operations on most operating systems. <?php ini_set ('include_path', '/var/log:/usr/var/log:.'); $url = 'compress.bzip2://logfile.bz2'; $fil = 'compress.zlib://foo1.gz'; $fr = fopen($url, 'rb', true); $fw = fopen($fil, 'wb1'); if (is_resource($fr) && is_resource($fw)) { while (!feof($fr)) { $data = fread($fr, 1024); fwrite($fw, $data); } fclose($fr); fclose($fw); } ?> This script first sets the include path to /var/log, /usr/var/log, and the cur- rent directory (.). Next, it tries to open the logfile.bz2 file from the include path and opens the foo1.gz file for writing with compression level 1. If both streams are opened successfully, the script reads from the bzipped file until it reaches the end and writes the contents directly into the gzipped file. When the script fin- ishes copying the contents, it closes the streams. Tip: Another great aspect about streams is that you can nest wrappers. For example, you can open them from the following URL: compress.zlib://http://www.example.com/foobar.gz

Post Comment
Login to post comments