0

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(); 
RedGiant
  • 4,444
  • 11
  • 59
  • 146

1 Answers1

1

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).

Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • 1
    @RedGiant: Or save files already compressed, like you suggested. It all depends on your needs. Now, when you have gziped saved cache file, you must set encoding to gzip, so browsers know what the data is: `if (file_exists($cachefile)) { header('Content-Encoding: gzip'); ...`. – Glavić Nov 05 '14 at 07:53