Reading and Writing .gz files in PHP

By David Sklar Viewed: 31748 times Emailed: 171 times Printed: 187 times Bookmark and Share



You want to read or write compressed files. Use PHP's zlib extension to read or write gzip'ed files. To read a compressed file:

$zh = gzopen('file.gz','r') or die("can't open: $php_errormsg");
while ($line = gzgets($zh,1024)) {
    // $line is the next line of uncompressed data, up to 1024 bytes 
}
gzclose($zh) or die("can't close: $php_errormsg");

Here's how to write a compressed file:

$zh = gzopen('file.gz','w') or die("can't open: $php_errormsg");
if (-1 == gzwrite($zh,$s))   { die("can't write: $php_errormsg"); }
gzclose($zh)                or die("can't close: $php_errormsg");

The zlib extension contains versions of many file-access functions, such as fopen(), fread(), and fwrite() (called gzopen(), gzread(), gzwrite(), etc.) that transparently compress data when writing and uncompress data when reading. The compression algorithm that zlib uses is compatible with the gzip and gunzip utilities.

For example, gzgets($zp,1024) works like fgets($fh,1024). It reads up to 1023 bytes, stopping earlier if it reaches EOF or a newline. For gzgets( ), this means 1023 uncompressed bytes.

However, gzseek() works differently than fseek(). It only supports seeking a specified number of bytes from the beginning of the file stream (the SEEK_SET argument to fseek( )). Seeking forward (from the current position) is only supported in files opened for writing (the file is padded with a sequence of compressed zeroes). Seeking backwards is supported in files opened for reading, but it is very slow.

The zlib extension also has some functions to create compressed strings. The function gzencode( )compresses a string and gives it the correct headers and formatting to be compatible with gunzip. Here's a simple gzip program:

$in_file = $_SERVER['argv'][1];
$out_file = $_SERVER['argv'][1].'.gz';

$ifh = fopen($in_file,'rb')  or die("can't open $in_file: $php_errormsg");
$ofh = fopen($out_file,'wb') or die("can't open $out_file: $php_errormsg");

$encoded = gzencode(fread($ifh,filesize($in_file)))
                             or die("can't encode data: $php_errormsg");

if (-1 == fwrite($ofh,$encoded)) { die("can't write: $php_errormsg"); }
fclose($ofh)                 or die("can't close $out_file: $php_errormsg");
fclose($ifh)                 or die("can't close $in_file: $php_errormsg");

The guts of this program are the lines:

$encoded = gzencode(fread($ifh,filesize($in_file)))
                             or die("can't encode data: $php_errormsg);
if (-1 == fwrite($ofh,$encoded)) { die("can't write: $php_errormsg"); }

The compressed contents of $in_file are stored in $encoded and then written to $out_file with fwrite( ).

You can pass a second argument to gzencode( ) that indicates compression level. Set no compression with 0 and maximum compression with 9. The default level is 1. To adjust the simple gzip program for maximum compression, the encoding line becomes:

$encoded = gzencode(fread($ifh,filesize($in_file)),9)
                             or die("can't encode data: $php_errormsg);

You can also compress and uncompress strings without the gzip-compatibility headers by using gzcompress()and gzuncompress().




Comments(2)


1. so if you then wanted to send this gzencoded data out the door via http - what headers would you use for content-type and content-encoding?

By: Mike at 2009-03-18 12:12:28
2. You should add the mime type as follows:

application/x-gzip

By: Anonymous at 2009-03-19 08:30:35

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:


Enter Code:
The Captcha image

Latest Tutorials

[2010-07-03]A Basic Example using PHP in AWS (Amazon Web Services)
[2010-07-03]Building a Video Sharing Site using PHP in AWS
[2010-06-30]XMLRPC for PHP - A simple client and server program
[2010-06-29]How to fix: Warning: Visiting this site may harm your computer - domainameat.cc
[2009-06-13]PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......
[2009-02-24]Using Text file as database in PHP
[2009-02-07]Parent: child process exited with status 3221225477 -- Restarting
[2009-01-14]Install and use PHPUnit to test your PHP pages for errors.
[2008-12-29]Using Codeigniter for PHP application development
[2008-12-01]Creating or Opening a File in PHP
[2008-12-01]Opening a Remote File in PHP
[2008-12-01]Reading contents of a File into a String in PHP
[2008-12-01]Counting Lines, Paragraphs, or Records in a File using pc_split_paragraphs() in PHP
[2008-12-01]Reading word by word from a file in PHP
[2008-12-01]Reading .ini files in PHP

More Latest News

Most Viewed Articles (in last 30 days)
isset() function in PHP
Reading .CSV file in PHP
Parent: child process exited with status 3221225477 -- Restarting
Handling BLOB in PHP and MySQL
Extract files from a .zip file using PHP
Find Difference between two dates in PHP
Appending One Array to Another in PHP
Upload and Download files with FTP in PHP
preg_split() and explode() in PHP
Reading and Writing .gz files in PHP
Install and use PHPUnit to test your PHP pages for errors.
public, protected, and private Properties in PHP
Reading word by word from a file in PHP
preg_match(), function preg_match_all(), preg_grep() in PHP
Using Text file as database in PHP
Most Emailed Articles (in last 30 days)
Opening a Remote File in PHP
Reading .CSV file in PHP
Counting Lines, Paragraphs, or Records in a File using pc_split_paragraphs() in PHP
Reading word by word from a file in PHP
Removing Duplicate Elements from an Array in PHP
Find Difference between two dates in PHP
Reading contents of a File into a String in PHP
PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......
isset() function in PHP
Setting cookies in PHP
Different versions of PHP - History and evolution of PHP
Traversing Arrays Using list() and each() in PHP
Creating or Opening a File in PHP
Extract files from a .zip file using PHP
Upload and Download files with FTP in PHP