Reading and Writing .gz files in PHP

By: David Sklar Emailed: 1646 times Printed: 2111 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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().


PHP Home | All PHP Tutorials | Latest PHP Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(3)


1. View Comment

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?

View Tutorial          By: Mike at 2009-03-18 12:12:28
2. View Comment

You should add the mime type as follows:

application/x-gzip


View Tutorial          By: Anonymous at 2009-03-19 08:30:35
3. View Comment

Thanks for this great tutorial... was looking for this kind of example.

View Tutorial          By: Shashi at 2012-09-20 11:35:08

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by David Sklar
Find Difference between two dates in PHP
Reading .CSV file in PHP
Appending One Array to Another in PHP
Removing Duplicate Elements from an Array in PHP
Sorting an Array in PHP
Iterating Through an Array in PHP
Password protecting a page in PHP
Deleting Cookies in PHP
Reading Cookie Values in PHP
Setting cookies in PHP
Encrypting and decrypting in PHP
GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP
Using Text-File Databases in PHP
Upload and Download files with FTP in PHP
Extract files from a .zip file using PHP

More Tutorials in PHP
PHP code to import from CSV file to MySQL
PHP code to write to a CSV file from MySQL query
PHP code to write to a CSV file for Microsoft Applications
Convert XML to CSV in PHP
Password must include both numeric and alphabetic characters - Magento
PHP file upload (Large Files)
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Error: Length parameter must be greater than 0
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Handling file locks in PHP
HTML table output using Nested for loops in PHP
Count occurrences of a character in a String in PHP

More Latest News
Most Viewed Articles (in PHP )
public, protected, and private Methods in PHP
preg_split() and explode() in PHP
PHP code to write to a CSV file from MySQL query
Convert a hex string into a 32-bit IEEE 754 float number in PHP
Upload and Download files with FTP in PHP
Function to return number of digits of an integer in PHP
func_get_arg() and func_get_args() functions in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Reading Cookie Values in PHP
Reading .CSV file in PHP
isset() function in PHP
Traversing Arrays Using foreach in PHP
public, protected, and private Properties in PHP
__toString() METHOD in PHP
Parent: child process exited with status 3221225477 -- Restarting
Most Emailed Articles (in PHP)
PHP code to write to a CSV file from MySQL query
PHP code to write to a CSV file for Microsoft Applications
Password must include both numeric and alphabetic characters - Magento
PHP code to import from CSV file to MySQL
Convert XML to CSV in PHP
Comparison operators in PHP
Using PEAR::Crypt_HMAC in PHP
GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP
Perl's Encoding::FixLatin equivalent in PHP
call_user_func() or call_user_func_array() functions in PHP
History and origin of PHP
isset() function in PHP
Binary Operators in PHP
if Statements in PHP
do...while Loops in PHP