php關於ob_start('ob_gzhandler')啟用GZIP壓縮的bug

來源:互聯網
上載者:User

標籤:測試   int   turn   port   顯示   ref   connect   test   lib   

 如果使用ob_start("ob_gzhandler"); 
則ob_clean()後面的輸出將不顯示,這是個bug,
可以用ob_end_clean();ob_start("ob_gzhandler"); 代替ob_clean();
否則後面輸出內容將是空。

<?php
error_reporting(E_ALL);
ob_start("ob_gzhandler");
echo "content";
ob_clean();
echo "more content";
?>
上面的代碼期望輸出more content實際上什麼內容也不會輸出。

下面就正常了
<?php
error_reporting(E_ALL);
ob_start("ob_gzhandler");
echo "content";
ob_end_clean();
ob_start("ob_gzhandler");
echo "more content";
?>

下面自訂一個回呼函數再測試
<?php
function my_ob_gzhandler($buffer,$mod){
   header("Content-Encoding: gzip");
   return gzencode($buffer, 9, FORCE_GZIP); 
}

error_reporting(E_ALL);
ob_start("my_ob_gzhandler");
echo "content";
ob_clean();
echo "more content";
?>
上面是正常的,但使用ob_end_clean代替ob_clean後又會導致後面的輸出不會顯示。

因此即使是下面的代碼依然會在使用ob_clean或者ob_end_clean後會導致輸出為空白。
<?php
if (ini_get(‘zlib.output_compression‘)) {
   if (ini_get(‘zlib.output_compression_level‘) != 9) {
      ini_set(‘zlib.output_compression_level‘, ‘9‘);
   } 
   ob_start();
} else {
   if (strstr($_SERVER[‘HTTP_ACCEPT_ENCODING‘], "gzip")) {
      ob_start("ob_gzhandler");
   } else {
      ob_start();
   } 

?>

最穩定的啟用頁面壓縮的方法應該類似下面
<?php
if(extension_loaded(‘zlib‘)) {
ini_set(‘zlib.output_compression‘, ‘On‘);
ini_set(‘zlib.output_compression_level‘, ‘3‘);
}
?>

但如果一定要使用ob_gzhandler來啟用頁面壓縮就要注意本文的第一句話了。

事實上,下面的代碼只是瀏覽器不顯示
error_reporting(E_ALL);
ob_start("ob_gzhandler");
echo "content";
ob_clean();
echo "more content";

但如果測試一下

telnet localhost 80
GET /test.php HTTP/1.0
<Enter>
<Enter>

將會返回如下資訊

HTTP/1.1 200 OK
Date: Fri, 20 Feb 2009 15:40:17 GMT
Server: Apache/2.2.6 (Win32) PHP/5.2.5
X-Powered-By: PHP/5.2.5
Vary: Accept-Encoding
Content-Length: 12
Connection: close
Content-Type: text/html

more content

失去了跟主機的串連。

可以看出more content已經輸出

但為何瀏覽器不顯示呢?

php關於ob_start('ob_gzhandler')啟用GZIP壓縮的bug

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.