Send gzipped PHP output to users browser’s to save bandwidth

This only works for Apache and you have to have the mod_gzip module loaded. This method is crap.

<?php
    ob_start("ob_gzhandler");
?>

So to send gzipped PHP output to users browser’s to save bandwidth, try this. It also helps for slow Internet connections and large pages too.

<?php
/**
 * Save this function in a file and include it on your page
 */
function print_gzipped_page() {
    global $HTTP_ACCEPT_ENCODING;
    if(headers_sent())
        $encoding = false;
    elseif( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false )
        $encoding = 'x-gzip';
    elseif( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false )
        $encoding = 'gzip';
    else
        $encoding = false;

    if($encoding) {
        $contents = ob_get_contents();
        ob_end_clean();
        header('Content-Encoding: '.$encoding);
        print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
        $size = strlen($contents);
        $contents = gzcompress($contents, 9);
        $contents = substr($contents, 0, $size);
        print($contents);
        exit();
    } else {
        ob_end_flush();
        exit();
    }
}

And then in your php page:

/**
 * Call this before you output anything.
 */
ob_start();
ob_implicit_flush(0);

/**
 * Do normal code here including creating objects, calling functions, echo, print, whatever.
 */
$obj = new SomeClass();
$arr = array();
echo "something";

/**
 * Call this function to output gzipped content.
 */
print_gzipped_page();

?>
Posted by admica   @   10 August 2009

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

Previous Post
« A faster way to write out all zeros to a disk using checksums
Next Post
Simple php function to check if post variables are set without triggering warnings »
Powered by Wordpress   |   Lunated designed by ZenVerse