Damaged data when gzipping

Posted by RadiantHeart on Stack Overflow See other posts from Stack Overflow or by RadiantHeart
Published on 2010-04-20T14:42:06Z Indexed on 2010/04/20 14:43 UTC
Read the original article Hit count: 209

Filed under:
|
|
|

This is the script I hva written for gzipping content on my site, which is located in 'gzip.php'. The way i use it is that on pages where I want to enable gzipping i include the file at the top and at the bottom i call the output function like this:

print_gzipped_page('javascript')

If the file is a css-file i use 'css' as the $type-argument and if its a php file i call the function without declaring any arguments. The script works fine in all browsers except Opera which gives an error saying it could not decode the page due to damaged data. Can anyone tell me what I have done wrong?

<?php
function print_gzipped_page($type = false) {
    if(headers_sent()){
        $encoding = false;
    }
    elseif( strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false ){
        $encoding = 'x-gzip';
    }
    elseif( strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false ){
        $encoding = 'gzip';
    }
    else{
        $encoding = false;
    }
    if ($type!=false) {
        $type_header_array = array("css" => "Content-Type: text/css", "javascript" => "Content-Type: application/x-javascript");
        $type_header = $type_header_array[$type];
    }

    $contents = ob_get_contents();
    ob_end_clean();
    $etag = '"' .  md5($contents) . '"';
    $etag_header = 'Etag: ' . $etag;
    header($etag_header);

    if ($type!=false) {
        header($type_header);
    }

    if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH']==$etag) {
        header("HTTP/1.1 304 Not Modified");
        exit();
    }

    if($encoding){
        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);
    }

    echo $contents;
    exit();
}

ob_start();
ob_implicit_flush(0);
?>

Additional info: The script works if the length og the document beeing compressed is only 10-15 characters.

© Stack Overflow or respective owner

Related posts about php

Related posts about gzip