Why is php gzip output not working for me?

半腔热情 提交于 2019-12-04 20:56:42

WHat's wrong?

probably nothing. GZIP compression is a completely transparent process between the server and the browser. The server will compress, and the browser will automatically uncompress the data. In the end result (= the HTML page's source code), nothing will change.

Use tools like Firebug or Chrome's developer tools to see whether the response was actually compressed.

In Chrome's Developer tools' "Network" tab, a compressed response will look something like this:

http://fhc.quickmediasolutions.com/image/-1775578843.png

When viewing the source code in the browser, you'll always see the decompressed version.

using apache mod_deflate is much more effective and comfortable… http://httpd.apache.org/docs/2.0/mod/mod_deflate.html

As a side tip: On a mobile I noticed that gzip wasn't working on some assets to finally discover that the assets were in application cache, so they weren't being retrieved from the server at all. Unfortunately Chrome audits isn't yet smart enough to know that cached assets don't need to be compressed and reports them as problems.

Maybe this might help.

<?php
function gzip_output() {
$HTTP_ACCEPT = $_SERVER['HTTP_ACCEPT_ENCODING'];

if (headers_sent()) {
    $encoding = false;
} elseif (strpos($HTTP_ACCEPT, 'x-gzip') !== false) {
    $encoding = 'x-gzip';
} elseif (strpos($HTTP_ACCEPT, 'gzip') !== false) {
    $encoding = 'gzip';
} else {
    $encoding = false;
}

if ($encoding) {
    $contents = ob_get_contents();
    ob_end_clean();
    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();
  } else {
     ob_end_flush();
     exit();
  }
}
  // At the beginning of each page call these two functions
  ob_start();
 ob_implicit_flush(0);

 // Then do everything you want to do on the page
 ?>
 <html>
 <body>
 <p>This should be a compressed page.</p>
  </html>
  <body>
  <?

// Call this function to output everything as gzipped content.
gzip_output();
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!