Search code examples
phphtmlcachingoutput-bufferingob-start

Compress cached output using PHP output buffers


By using this one line code ob_start('ob_gzhandler'); at the top of the page, the php output was about 11 kb according to Chrome console. When I tried to cache the output with the following code, I found the cached file was saved about 65kb. Is the bigger output size the trade off for caching? Is there any way to compress the cached output further? I have tried adding some htaccess rules for html compression but I don't think that helps.

$id = $_GET["id"];
$cachefile ="cache/p_{$id}.html";
if (file_exists($cachefile)) {
 include($cachefile);
 echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
 exit;
}
ob_start('ob_gzhandler');

$fp = fopen($cachefile, 'w'); // open the cache file for writing
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
fclose($fp); // close the file
ob_end_flush(); 

Solution

  • Your cached file was not gziped by the server, try this way:

    ob_start('ob_gzhandler');
    $id = $_GET["id"];
    $cachefile ="cache/p_{$id}.html";
    if (file_exists($cachefile)) {
        include($cachefile);
        echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
    } else {
        // your html or something else ...
        $fp = fopen($cachefile, 'w'); // open the cache file for writing
        fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
        fclose($fp); // close the file
    }
    ob_end_flush(); 
    

    p.s. I would leave this task of compressing to the web server (nginx, apache).