tags:

views:

142

answers:

3

Hello,

Here is my PHP Code

$phpver = phpversion();

$useragent = (isset($_SERVER["HTTP_USER_AGENT"]) ) ? $_SERVER["HTTP_USER_AGENT"] : $HTTP_USER_AGENT;
$do_gzip_compress = FALSE;

if ($phpver >= '4.0.4pl1' && (strstr($useragent,'compatible') || strstr($useragent,'Gecko'))) {
    if (extension_loaded('zlib')) {
     ob_start('ob_gzhandler');
    }
} 

header('Content-type: text/javascript;charset=utf-8');
header('Expires: '.gmdate("D, d M Y H:i:s", time() + 3600*24*365).' GMT');

echo "TEST";

I basically want to cache the content (on client side) forever as well as gzip it. However I am not sure if the above is the best way. I do not want to use any third party scripts. Is my client side caching headers enough? Do I need to add more? Also, will this interfere with Apache's native gzipping (which is turned on the server)- will it gzip twice?

Thank you for your time.

A: 

If you have root access, edit php.ini and add the following to automatically gzip your php pages.

zlib.output_compression = On
zlib.output_compression_level = 1

then, your actual php page can be:

<?php
$expires = 3600*24*365;
header("Cache-Control: maxage=".$expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');

echo 'test';
?>
jusunlee
A: 

It's not a big deal but ob_start('ob_gzhandler') will return false (and not turn on output buffering) if the client's browser does not support gzip encoding, so you can eliminate the user agent tests.

Jay Paroline
+1  A: 

ob_gzhandler will automatically detect if the users browser is gz compatible.

It will also automatically modify your headers.

It won't detect if apache is running mod_deflate or mod_gzip (and who says your using Apache anyway!)

if(!ob_start("ob_gzhandler")) ob_start();

/* insert code here then flush the buffer to $buffer */

    $cacheTime = time(); // or the file date of your static file

    $gmt_mtime = gmdate('D, d M Y H:i:s', $cacheTime ) . ' GMT';
    header("Content-type: text/css; charset=utf-8");
    header("Last-Modified: " . $gmt_mtime ,true);
    header('Content-Length: ' . strlen($buffer),true);
    header("Expires: " . gmdate("D, d M Y H:i:s", $cacheTime + $seconds) . " GMT",true);
    header("Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate",true);
    header("Cache-Control: post-check=0, pre-check=0", FALSE);

echo $buffer;
Justin Alexander