Using Bzip2 Archives


 file_put_contents("compress.bzip2://$bzip2file", $data); 


Another file format that does not come with all operating systems, but offers great compression rates, is Bzip2. Here, PHP also has a built-in stream wrapper: compress.bzip2://. To use this, you have to load the Bzip2 library from http://sources.redhat.com/bzip2/. Then use the configuration switch with-bzip2 (UNIX/Linux), or write extension=php_bzip2.dll in your php.ini configuration file (Windows). Then you are ready to go and can compress or decompress files, as can be seen in the preceding code, which uses file_get_contents() and file_put_contents().

Zipping and Unzipping a File with Bzip2 (bzip2.php; excerpt)
 <?php   $filename = __FILE__;   $bzip2file = "$filename.bz2";   $data = file_get_contents(__FILE__);   echo 'Loaded file (size: ' . strlen($data) .     ').<br />';   file_put_contents("compress.bzip2://$bzip2file",     $data);   echo 'Bzipped file (new size: ' . filesize     ($bzip2file) . ').<br />';   $data = file_get_contents("compress.bzip2://    $bzip2file");   echo 'Original file size: ' . strlen($data) . '.'; ?> 

Alternatively, you can use PHP's special Bzip2 functions. They work very similarly to PHP's file functions. However, for writing, you have to use bzopen(), bzwrite(), and bzclose() instead of fopen(), fwrite(), and fclose(), as the following code shows, which creates a function file_put_bzip2_contents().

Zipping a File with BZip2 (bzip2write.php)
 <?php   function file_put_bzip2_contents($filename,     $content) {     if ($fp = @bzopen($filename, 'wb')) {       $result = bzwrite($fp, $content);       bzclose($fp);       return $result;     } else {       return false;     }   }   file_put_bzip2_contents('file.txt.bz2',     "\n> This text file contains\nsome random text.         <");   echo 'Data written to file.'; ?> 

The other direction (reading a file from a BZip2 archive) works analogously to reading a regular file. Instead of fopen(), fread(), and fclose(), you use bzopen(), bzread(), and bclose(), as can be seen in the following code, which writes a function file_get_bzip2_contents().

Unzipping a File with BZip2 (bzip2read.php)
 <?php   function file_get_bzip2_contents($filename) {     $result = '';     if ($fp = @bzopen($filename, 'wb')) {       while ($data = bzread($fp, 4096)) {         $result .= $data;       }       bzclose($fp);       return $result;     } else {       return false;     }   }   echo nl2br(htmlspecialchars(     file_get_bzip2_contents('file.txt.bz2')   )); ?> 




PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net