ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ob_gzhandler — ob_start callback function to gzip output buffer

Description

stringob_gzhandler
( string$buffer
, int$mode
)

ob_gzhandler() is intended to be used as a callback
function for ob_start() to help facilitate sending
gz-encoded data to web browsers that support compressed web pages.
Before ob_gzhandler() actually sends compressed data,
it determines what type of content encoding the browser will accept
("gzip", "deflate" or none at all) and will return its output accordingly.
All browsers are supported since it's up to the browser to send the
correct header saying that it accepts compressed web pages. If a browser
doesn't support compressed pages this function returns FALSE.

User Contributed Notes 40 notes

<?php// do not useob_start("ob_gzhandler");// along withheader('HTTP/1.1 304 Not Modified');

// or in the end useob_end_clean();?>

W3C Standart requires response body to be empty if 304 header set. With compression on it will at least contain a gzip stream header even if your output is completely empty!

This affects firefox (current ver.3.6.3) in a very subtle way: one of the requests after the one that gets 304 with not empty body gets it response prepended with contents of that body. In my case it was a css file and styles was not rendered at all, which made problem show up.

- the "mode" arg accepts a bit field composed of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END. See http://www.php.net/manual/fr/ref.zlib.php#56216 for an example. The value that jazfresh recommends below (5) is the good one, because 5 == PHP_OUTPUT_HANDLER_START | PHP_OUTPUT_HANDLER_END.

- when called INSIDE an output buffering handler, ob_gzhandler DOES NOT return false when the browser doesn't support compressed pages. It rather returns the original string.

In the set_error_handler notes, there is a technique described for capturing all errors (even parse errors) before they are displayed the user, using a special error handler and output handler. If this output handler detects a fatal error in the output buffer, it's captured and dealt with before it can be displayed to the user. If no error was detected, then output buffer is displayed verbatim (i.e. without being compressed).

If you are using this method, you can still take advantage of ob_gzhandler's compression. However, you MUST specify a mode argument (I'm using 4.2.2 on RedHat9). The mode value affects which headers are automatically added (Content-Encoding, etc). A value of '5' worked for me. '0' or discarding the argument produces a blank screen under Mozilla.

Someone previously mentioned that MSIE doesn't cache gzipped content. This is false. He misread the source of information. In fact, IE will cache gzipped content no matter what. Here is the quote from the mailing list:

The reason the COMPRESSED responses are, in fact,always getting cached no matter what "Vary:" field nameis present is just as I suspected... it is because MSIEdecides it MUST cache responses that arrive with"Content-Encoding: gzip" because it MUST have adisk ( cache ) file to work with in order to do thedecompression.

Please be aware that, as other users have already mentioned, the compression will fail if there are characters before the php start tag "< ?".

This is also the case when saving files in UTF-8 format with editors such as Ultraedit. Make sure you save the file using the defined option UTF-8 NO BOM or delete the BOM otherwise the two UTF BOM characters will be written at the start of the file.

When using ob_start("ob_gzhandler"), be aware that the output buffer has to be flushed in order to invoke the ob_gzhandler callback function.

This may not always happen. For example, if you use ob_get_contents() to copy the output buffer to a string for further manipulation and then silently discard the buffer with ob_end_clean(), the output buffer is never "flushed" and as a result, the ob_gzhandler callback function is never invoked. And your pages won't be compressed.

This will be the case, for example, if you use the PHP Fusebox architecture/framework.

if you call ob_end_clean() after ob_start("ob_gzhandler"), the "Content-Encoding: gzip" header will still get sent (assuming the browser supports the encoding). if you don't call ob_start() again with the ob_gzhandler callback function, the output will not be compressed, but the header will say it is. this causes mozilla (as of build 2002032808) to display a blank page.

I have a very well tested module in my framework (ie: running in production environments for a couple of years) called 'fastpage', which takes care of both memcaching and gzipping for frequently requested content. It memcaches one version of each unique page both gzipped and non-gzipped, and returns the appropriate version based upon the browser's Accept-encoding header.

Unfortunately, on IE8 beta (in IE8 mode, or in IE7 emulation mode), the fastpage-enabled content was not being un-gzipped. IE would request the content, a 200 status and correct byte count would appear in the server logfile, and IE would show no errors. However, CSS would not be applied and Javascript would not execute.

The only fix I can find right now is to disable gzip entirely for this browser. User agent string is: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727

The same output works fine in firefox (windows, linux, mac), and in safari.

Your 'solution' doesn't really work since session_id() will return an empty string if there is no session started. Therefore it will never return NULL.Yes the problem is gone, but also is your output buffering xD

I haven't found a solution to this problem yet... It seems ie6 just doesn't wanna play nice - like it does most of the times.

faisun at sina dot com:If you read up on output buffering, you'll see that if an output buffer callback returns false, this instructs PHP to output the original string untouched. That's why ob_gzhandler() returns false if the encoding is not supported. When ob_start("ob_gzhandler") is used and encoding is not supported, ob_gzhandler() will return false and PHP outputs the original, uncompressed string.

jsnell at e-normous dot com:Output buffering callback functions accept up to two parameters, so this would probably work better for your situation:

When writing scripts for distribution, I would usually "null" out the following deprecated superglobals so that users who uses the script will not be able to use them.<?php$HTTP_GET_VARS = null;$HTTP_POST_VARS = null;$HTTP_COOKIE_VARS = null;$HTTP_POST_FILES = null;$HTTP_SERVER_VARS = null;?>

However, when using ob_start('ob_gzhandler'), one of those superglobals somehow disable this function.

According to the manual, if ob_gzhander detects that the browser is unable to support deflate or gzip it returns FALSE. Does this mean that if you use ob_start("ob_gzhandler"), any browsers that do not support gzip/deflate will receive a blank page?

I've been having problems with IE6 displaying gzipped pages and adding a test:

So why doesn't the web server just do this by default? This works for me if I do:ini_set('zlib.output_compression_level', 3); ob_start("ob_gzhandler"); or even just:ob_start("ob_gzhandler");

I did the level 3 compression, I think the default was 6 and I didn't want to put too much load on the server. For a 895k file (my largest) the compression levels were:1 = 189k3 = 178k4 = 163k6 = 156k (I believe 6 is the default if you leave out the ini_set)9 = 155kI use http://www.whatsmyip.org/mod_gzip_test/ to check the sizes.

FYI: This works with dynamic files in Movable Type 3.x (I'm testing it in 3.2) I've got the above command in the first line of my mtview.php file.

i had a LOT of trouble trying to get gzipping working correctlyi kept getting a blank page on the first load, although subsequent pages loaded fine.i tried stuff with ob_flush and ob_end_clean and all kinds of stuff i didn't understand. i'm totally confused about different versions of php and different methods of gzipping.

in the end, i got it working (maybe i'll understand it later).i ended up using phpBB's code (stripped of non-gz stuff, and ever-so-slightly modified)http://phpbb.com/

To pass the second argument to ob_gzhandler() which specifies what level of compression should be used (which I assume is 1-9 as with the gzip binary, with 9 using the most processor and time to do, 4 is the standard IIRC) you must call ob_start() like so:

zlib.output_compression runs in parallel with script execution - it begins compressing as soon as it receives any output from your script, and sends data to the client each time its buffer (4K by default) gets full. ob_gzhandler (actually 'ob_start("ob_gzhandler");') will not start compressing until the script flushes (or, usually, exits), and will in turn send the entire compressed document at once - which makes it more susceptible to causing a perception of latency.

Advantage: zlib.output_compression

On the other hand, ob_gzhandler gives you script-level control allowing you to use it selectively or to unset it after setting it in certain cases. Despite some documentation to the contrary, zlib.output_compression does not appear to be able to be set or unset on a script level; you must instead set it globally (in php.ini) or in your webserver configs or .htaccess files, possibly using FilesMatch-type mechanisms to control which scripts it will or won't apply to - which could get unwieldy for large projects - particularly those which employ PHP to produce images and other non-text output in addition to normal text output.

Advantage: ob_gzhandler

Net advantage: depends on your particular needs. I'm trying zlib.output_compression for now, but I miss the flexibility that ob_gzhandler would provide.

<FilesMatch "\.(php|html?)$"># turn it on with the buffer set to 2K using php_valuephp_value zlib.output_compression 2048# or just turn it on using php_flag# php_flag zlib.output_compression On</FilesMatch>

I have noticed that if you have the php setting for zlib.output_compression set to 'On' AND you attempt to use hte ob_gzhandler handler to ob_start () the output you get in the browser WILL be garbled in PHP 4.2.3. I'm guessing that the output buffering is compressing the output to be sent, and then zlib is doing it a second time, but the browser is only uncompressing it once.

But using either one will give you the same results (compressed output from the script)

If you are trying to use the ob_gzhandler in a MSHTA (Microsoft HTML Application) you will find that your pages does not show up. the MSHTA-browser probably says it can handle gzip, but it just won't work (IE:6, PHP:4.1.2)

RFC 2616 suggests that a more correct way to compress documents on the fly is to use gzip transfer encoding rather than gzip content encoding. However, it's perhaps not advisable to use this since client support for it is extremely limited.

The difference is most evident when you come to save a file from your browser. If it's gzip content encoded then the browser should (and may well) save it gzipped. If it's gzip transfer encoded then the browser should uncompress it first.

To get this to work properly, you have to compile PHP with "--with-zlib". If you don't, you won't get any errors, it just won't actually compress anything. This is a phenomenal thing. For just a small bit of processor time, you can DRASTICALLY reduce the bandwidth requirement of your scripts. There are very few circumstances in which this should not be used.

i can think of two good reasons not to compress your error pages:1. You want to make sure that people can read you error pages, don't you ?2. Compressing pages have a "side effect" : it's smaller !! if you return "HTTP/1.x 404 Document Not fount" (or any other HTTP error), MSIE will display it's built in error message, not yours if it's small than 513bytes. (see "HOW TO: Turn Off the Internet Explorer 5.x and 6.x 'Show Friendly HTTP Error Messages' Feature on the Server Side" http://support.microsoft.com/default.aspx?scid=kb;en-us;Q294807 )

No matter the circumstances, you MUST NOT check the user agent string to find out if gzip compression is enabled. HTTP defines the Accept-Encoding header for exactly this purpose and you MUST check it before enabling compression.

You should know about:* Internet Explorer 5.x,6 should turned to HTTP 1.1 to get "Accept-Encoding: gzip"* In Mozilla 1.0 RC2 you can write the "Accept-Encoding:" in Preferences/Advanced/HTTP Networking

exit;
?>
I wouldn't recommande using level 9, waste of CPU, something between 1 and 6 would be more resonable
I have tested without the substr/crc/size and it worked flawlessly in IE5/5.5/6, Opera7.11/7.21, IE5.5 MAC

It may seem obvious but if you use ob_start("ob_gzhandler"), make sure no content is unintentionally echo'ed before : this could be blank lines before '<?php' or after '?>' tags in included files or even errors.

Otherwise, only a part of the content (the content sent after ob_start()) will be compressed, which will confuse the client.

Setting compression using zlib.output_compression either in php.ini or in Apache configuration file (with directive php_flag) is safer in this regard.