Third party cookies may be stored when visiting this site. Please see the cookie information.

PHP Programming: Reading and Writing to GZip Files

In the past I've mainly created my web server-side applications using Perl. Recently though I've been using PHP quite a bit. I'm not going to go into the arguments for and against these two different programming languages (I'll save that for another day), but instead I've found a nice feature of PHP that I thought I'd share.

PHP has built in Zlib module which provides the ability to read and write compressed files (they are similar modules available for Perl). GZip is a commonly used compression algorithm creating files ending with .gz. Files compressed with gzip are usually much smaller than the raw files (although that depends upon the amount of redudancy in the original file).

To read a normal (not compressed) file in using PHP can be as simple as:

$lines = file ($filename);

which puts each line into the array $lines, one line of text per entry.

e.g. $lines[0] is the first line of the file, $lines[1] is the second.

If the file you wanted to read is gzipped (ie. compressed with gzip), then you just need to change that to:

$lines = gzfile ($filename);

so if you wanted to read in a file and output it to STDOUT you just use:


$lines = gzfile('somefile.gz');

foreach ($lines as $line) {

   echo $line;



this can also be achived using:

readgzfile ($filename);

which is even shorter, although the earlier example using gzfile has the advantage that you have an array that you can perform any manipulations on before outputting.

There are a whole selection of compression functions available from the Zlib Module page.

You wouldn't want to use compression on pages that are very popular as the load on the server would be higher, but they can help reduce the space required for some rarely accessed information.

» PenguinTutor Facebook page