Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : Zlib Compression Functions

Zlib Compression Functions


This module enables you to transparently read and write gzip (.gz) compressed files, through versions of most of the filesystem functions which work with gzip-compressed files (and uncompressed files, too, but not with sockets).


Version 4.0.4 introduced a fopen-wrapper for .gz-files, so that you can use a special zlib: URL to access compressed files transparently using the normal f*() file access functions if you prefix the filename or path with zlib: when calling fopen(). This feature requires a C runtime library that provides the fopencookie() function. Up to now the GNU libc seems to be the only library that provides this feature.

In PHP 4.3.0, zlib: has been changed to compress.zlib:// to prevent ambiguities with filenames containing ':' characters. The fopencookie() function is not longer required. More information is available in the section about the section called “Compression Streams”.


This module uses the functions of » zlib by Jean-loup Gailly and Mark Adler. You have to use a zlib version >= 1.0.9 with this module.


Zlib support in PHP is not enabled by default. You will need to configure PHP --with-zlib[=DIR]

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Built-in support for zlib on Windows is available with PHP 4.3.0.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

The zlib extension offers the option to transparently compress your pages on-the-fly, if the requesting browser supports this. Therefore there are three options in the configuration file php.ini.

Table 346. Zlib Configuration Options

Name Default Changeable Changelog
zlib.output_compression "0" PHP_INI_ALL Available since PHP 4.0.5.
zlib.output_compression_level "-1" PHP_INI_ALL Available since PHP 4.3.0.
zlib.output_handler "" PHP_INI_ALL Available since PHP 4.3.0.

For further details and definitions of the PHP_INI_* constants, see the Appendix I, php.ini directives.

Here's a short explanation of the configuration directives.

zlib.output_compression boolean/integer

Whether to transparently compress pages. If this option is set to "On" in php.ini or the Apache configuration, pages are compressed if the browser sends an "Accept-Encoding: gzip" or "deflate" header. "Content-Encoding: gzip" (respectively "deflate") and "Vary: Accept-Encoding" headers are added to the output. In runtime, it can be set only before sending any output.

This option also accepts integer values instead of boolean "On"/"Off", using this you can set the output buffer size (default is 4KB).


output_handler must be empty if this is set 'On' ! Instead you must use zlib.output_handler.

zlib.output_compression_level integer

Compression level used for transparent output compression.

zlib.output_handler string

You cannot specify additional output handlers if zlib.output_compression is activated here. This setting does the same as output_handler but in a different order.

Resource Types

This extension defines a file pointer resource returned by gzopen().

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FORCE_GZIP (integer)


This example opens a temporary file and writes a test string to it, then it prints out the content of this file twice.

Example 2719. Small Zlib Example


= tempnam('/tmp', 'zlibtest') . '.gz';
$s = "Only a test, test, test, test, test, test, test, test!\n";

// open file for writing with maximum compression
$zp = gzopen($filename, "w9");

// write string to file
gzwrite($zp, $s);

// close file

// open file for reading
$zp = gzopen($filename, "r");

// read 3 char
echo gzread($zp, 3);

// output until end of the file and close it.


// open file and print content (the 2nd time).
if (readgzfile($filename) != strlen($s)) {
"Error with zlib functions!";


Table of Contents

gzclose — Close an open gz-file pointer
gzcompress — Compress a string
gzdecode — Decodes a gzip compressed string
gzdeflate — Deflate a string
gzencode — Create a gzip compressed string
gzeof — Test for end-of-file on a gz-file pointer
gzfile — Read entire gz-file into an array
gzgetc — Get character from gz-file pointer
gzgets — Get line from file pointer
gzgetss — Get line from gz-file pointer and strip HTML tags
gzinflate — Inflate a deflated string
gzopen — Open gz-file
gzpassthru — Output all remaining data on a gz-file pointer
gzputs — Alias of gzwrite()
gzread — Binary-safe gz-file read
gzrewind — Rewind the position of a gz-file pointer
gzseek — Seek on a gz-file pointer
gztell — Tell gz-file pointer read/write position
gzuncompress — Uncompress a compressed string
gzwrite — Binary-safe gz-file write
readgzfile — Output a gz-file
zlib_get_coding_type — Returns the coding type used for output compression

Code Examples / Notes » ref.zlib


zlib.output_compression has caused problems for me in IE 6, when pages are sometimes not displayed. This could be difficult to track down and PHP have no intention of fixing it, so hopefully you find this note in a search if it happens to you.


The method of first reading the source file and then passing its content to the gzip function instead of simply the source and destination filename was a bit confusing for me.
So I have written a simple funtion you can use to compress files in the gzip format (gzip is readable by winzip like .zip files)
function compress($srcName, $dstName)
 $fp = fopen($srcName, "r");
 $data = fread ($fp, filesize($srcName));
 $zp = gzopen($dstName, "w9");
 gzwrite($zp, $data);
// Compress a file
compress("/web/myfile.dat", "/web/myfile.gz");


Run, do not walk, run, to add this to your Apache config file:
php_flag zlib.output_compression On
php_value zlib.output_compression_level 5
I just tried this and achieved 10x and 15x speed inprovement on
some mature php pages.  Pages I have been seating over to make 5% gains on.  I use microtime() on critical pages to help me track page speed and that confirms the speed improvement.  The php page takes a timestamp at the beginning and end, then logs the page duration.  So any IP transmission effects are not included.  There is
a clear subjective difference to the user.
The test system was PHP 4.3.6, Apache 2.0.49 over Linux 2.4.
As always YMMV.


register_shutdown_function() ( won't output anything if you use zlib.output_compression.
Shutdown function is called after closing all opened output buffers thus, for example, its output will not be compressed if zlib.output_compression is enabled.

arne dot heizmann

PHP Version 5.1.4 here. What Bob said is correct even in this version (newest at the time of writing). You can't enable zlib.output_compression via ini_set(). You have to use php.ini.


php at seven dot net dot nz:
Have you been using register_shutdown_function() that outputs something? If yes, some of the output was not encoded and IE6 is less than forgiving about that. In my case it was reloading the page and sometimes showing a blank page. So IE6 does get invalid stream, bug is not bogus, only description is not good enough.
jpleveille at webgraphe dot com:
In PHP 4.4.2 register_shutdown_function() DOES output whatever you wish, but it is not encoded with the rest of the document. Which is even worse as you get a bug that is difficult / impossible to track down.


Nice function. I did it the other way round:
function uncompress($srcName, $dstName) {
  $zp = gzopen($srcName, "r");
       $string .= gzread($zp, 4096);
  $fp = fopen($dstName, "w");
  fwrite($fp, $string, strlen($string));
uncompress("./myfile.txt.gz", "./myfile.txt");
A shorter approach would be:
function uncompress($srcName, $dstName) {
 $string = implode("", gzfile($srcName));
 $fp = fopen($dstName, "w");
 fwrite($fp, $string, strlen($string));


My gzip function.
This function read, compress and writhe only small chunks at one time, this way you can compress big files without memory problems...
function gzip($src, $level = 5, $dst = false){
if($dst == false){
$dst = $src.".gz";
$filesize = filesize($src);
$src_handle = fopen($src, "r");
$dst_handle = gzopen($dst, "w$level");
$chunk = fread($src_handle, 2048);
gzwrite($dst_handle, $chunk);
return true;
} else {
error_log("$dst already exists");
} else {
error_log("$src doesn't exist");
return false;


If you use "zlib.output_compression = On" in your php.ini file, and activates output buffering (ob_start), don't output this header :
header('Content-Length: '.ob_get_length());
This is because ob_get_length() will return the uncompressed size while zlib will compress the output. Thus your browser will get confused waiting for extra data that will never come.


If you turn zlib.output_compression_level on, be advised that you shouldn't try to flush() the output in your scripts. PHP will add the gzip header but send the output uncompressed, which plays havoc with Mozilla. IE seems to handle it, though.


If you need to compress data and send it as "Content-disposition: attachment" and on-the-fly to the client due to the size for example (40Mb) here's a dirty trick using ob_gzhandler()
Keep in mind that $str is the content to output.
When you start the output call
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_START);
Then to output any further content
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_CONT);
And to close the output
echo ob_gzhandler('', PHP_OUTPUT_HANDLER_END);
Only tested on Apache 1.3.33 with PHP 5.0.4


If you have zlib.output_compression set to on when your script starts (in php.ini or via apache directive), then you disable it at runtime using ini_set() before producing output, your output will still be buffered!  Even if you call ob_implicit_flush().
If you want unbuffered output, you must disable zlib.output_compression before your script starts (as well as mod_gzip of course, if you have both installed).
This behaviour experienced on Server: Apache/1.3.33 (Debian GNU/Linux) mod_gzip/ PHP/4.3.10-18


I tested all the compression levels against a 22k page and here are the results I got (in bytes):
off = 22549
1 = 4297
2 = 4279
3 = 4264
4 = 4117
5 = 4097
6 = 4063
7 = 4011
8 = 3998
9 = 3996
Looks like the best bets for zlib.output_compression_level is 1 or 5.  The default of 6 is probably OK too.  Don't know what the CPU usage difference is between them all though.


I found the absolute easiest way to read a gzip file is as follows:
echo file_get_contents("compress.zlib:///myphp/test.txt.gz");
To create a gzip file:
file_put_contents("compress.zlib:///myphp/test.txt.gz","Put this in the file\r\n");
Things to note about this:
-The best prefix to use is "compress.zlib", not "zlib"
-If you wish to specify a path starting in the root path, you actually end up with three slashes.  The above path corresponds to "/myphp/test.txt" on unix, and "c:\myphp\test.txt" on Windows (if C: is the current drive).  I tested it just on Windows.
-Compression and decompression both use the same prefix of "compress.zlib://" (plus one more slash to get a root dir).
-I'm using 5.0, so I'm not 100% sure which behaviour started in which version.


Have a look to this extended version :)
function compress( $srcFileName, $dstFileName )
// getting file content
$fp = fopen( $srcFileName, "r" );
$data = fread ( $fp, filesize( $srcFileName ) );
fclose( $fp );

// writing compressed file
$zp = gzopen( $dstFileName, "w9" );
gzwrite( $zp, $data );
gzclose( $zp );
function uncompress( $srcFileName, $dstFileName, $fileSize )
// getting content of the compressed file
$zp = gzopen( $srcFileName, "r" );
$data = fread ( $zp, $fileSize );
gzclose( $zp );

// writing uncompressed file
$fp = fopen( $dstFileName, "w" );
fwrite( $fp, $data );
fclose( $fp );
compress( "tmp/supportkonzept.rtf", "tmp/_supportkonzept.rtf.gz" );
uncompress( "tmp/_supportkonzept.rtf.gz", "tmp/_supportkonzept.rtf", filesize( "tmp/supportkonzept.rtf" ) );


For decompressing, i modified a function posted earlier (that way $string doesn't have a big size that may be beyond the memory limit if the gzipped file is big) :
function file_ungzip($fromFile, $toFile) {
$zp = @gzopen($fromFile, "r");
$fp = @fopen($toFile, "w");
while(!@gzeof($zp)) {$string = @gzread($zp, 4096); @fwrite($fp, $string, strlen($string));}


Contrary to what the documentation says, I've been unable to get zlib.output_compression to work via ini_set() (Even though I put it at the very beginning of the file before any output was sent) as of php 4.3.11.  While it does get set to true, it will not actually do anything. Which means if you don't set this via php.ini or Apache configuration it's a no-go. I have to use ob_start("ob_gzhandler"); instead.


An alternate way to handle gzip compression is to let the mod_gzip module of apache handle it. This seems to contradict the tutorial on saying that it won't compress php (or any dynamic) output, but mod_gzip as of version works well for me.
Here is an example of an httpd.conf setup:
<IfModule mod_gzip.c>
mod_gzip_on                 Yes
mod_gzip_dechunk            Yes
mod_gzip_minimum_file_size  300
mod_gzip_maximum_file_size  0
mod_gzip_maximum_inmem_size 100000
mod_gzip_keep_workfiles     No
mod_gzip_temp_dir           /tmp
mod_gzip_item_include       file \.html$
mod_gzip_item_include       file \.jsp$
mod_gzip_item_include       file \.php$
mod_gzip_item_include       file \.pl$
mod_gzip_item_include       mime ^text/.*
mod_gzip_item_include       mime ^application/x-httpd-php
mod_gzip_item_include       mime ^httpd/unix-directory$
mod_gzip_item_include       handler ^perl-script$
mod_gzip_item_include       handler ^server-status$
mod_gzip_item_include       handler ^server-info$
mod_gzip_item_exclude       mime ^image/.*
This will automatically compress all output of your files with the .php extention or the x-httpd-php mime type. Be sure to have dechunk set to Yes.


* @return bool
* @param string $in
* @param string $out
* @param string $param = "1"
* @desc compressing the file with the zlib-extension
function gzip ($in, $out, $param="1")
if (!file_exists ($in) || !is_readable ($in))
return false;
if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
return false;

$in_file = fopen ($in, "rb");
if (!$out_file = gzopen ($out, "wb".$param)) {
return false;

while (!feof ($in_file)) {
$buffer = fgets ($in_file, 4096);
gzwrite ($out_file, $buffer, 4096);
fclose ($in_file);
gzclose ($out_file);

return true;
* @return bool
* @param string $in
* @param string $out
* @desc uncompressing the file with the zlib-extension
function gunzip ($in, $out)
if (!file_exists ($in) || !is_readable ($in))
return false;
if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
return false;
$in_file = gzopen ($in, "rb");
$out_file = fopen ($out, "wb");
while (!gzeof ($in_file)) {
$buffer = gzread ($in_file, 4096);
fwrite ($out_file, $buffer, 4096);

gzclose ($in_file);
fclose ($out_file);

return true;

Change Language

Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Haru PDF Functions
hash Functions
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker