I was testing my website with Page Speed and the result was around 70/100. Enable Compression was the first and most important factor in slowing it down.
I know that
I'd suggest to use http://php.net/manual/de/function.ob-gzhandler.php, this works out of the box for me:
In my index.php I just place this before some output:
/**
* Enable GZIP-Compression for Browser that support it.
*/
ob_start("ob_gzhandler");
And it encodes it!
A few things:
You probably want to add another header: header('Content-Encoding: gzip');
You are using ob_end_clean, which deletes all echoed/printed content without sending it to the browser. Depending on what you're trying to do, you may want to use ob_flush instead.
To make sure your output is buffered and handled (and compressed if you use PHP's output buffering compression), make sure all echo/print statements are placed BETWEEN the ob_start and ob_flush sttements.
--and then try it again :)
Well, I think it's because you're trying to compress an empty string.
I took your script as you gave it, and ran it in FF and IE.
Both failed, and FF said that there was an issue (like you described).
However, I then noticed $data is an empty string.
When I set $data = "Some test data.";
at the top of the file it worked immediately (browser displayed "Some test data."), and checking in Firebug, I can see the correct headers.
Content-Encoding gzip
Content-Length 68
Vary Accept-Encoding
Content-Type text/html
Edit: Also, just to point out, your if ($supportsGzip) {
is a bit odd, because your else condition should actually echo out $data
, not $content
.
Edit: Okay, based on your revised function above, there are two key problems.
The primary problem has to do with the fact that you're wiping out your headers by calling ob_end_clean()
. A comment on the PHP Docs states that "ob_end_clean() does discard headers".
This means any headers you set before calling ob_end_clean()
will get wiped. Also, your revised function doesn't send a gzip encoding header, either.
I must say that there is probably no need to even use ob_start and related functions here, either. Try the following:
function _compress( $data ) {
$supportsGzip = strpos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) !== false;
if ( $supportsGzip ) {
$content = gzencode( trim( preg_replace( '/\s+/', ' ', $data ) ), 9);
header('Content-Encoding: gzip');
} else {
$content = $data;
}
$offset = 60 * 60;
$expire = "expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header("content-type: text/html; charset: UTF-8");
header("cache-control: must-revalidate");
header( $expire );
header( 'Content-Length: ' . strlen( $content ) );
header('Vary: Accept-Encoding');
echo $content;
}
_compress( "Some test data" );
This works in IE and FF, but I didn't have time to test other browsers.
If you really must use ob_start and related functions, make sure you set your headers after you call ob_end_clean()
.