PHP如何開啟gzip提升網頁響應速度

來源:互聯網
上載者:User
本文主要和大家分享PHP如何開啟gzip提升網頁響應速度,希望能協助到大家。

1、apache開啟gzip(此方式需要重啟伺服器):

a.開啟模組:

LoadModule deflate_module modules/mod_deflate.soLoadModule headers_module modules/mod_headers.so

b.httpd.conf中增加

<ifmodule deflate_module>  DeflateCompressionLevel 9  AddOutputFilterByType DEFLATE text/html text/plain text/xml application/json application/xml  AddOutputFilter DEFLATE js css  AddOutputFilter INCLUDES .shtml .htm .xml .php .html</ifmodule>

c.重啟伺服器

2、php開啟gzip

原理:

header("Content-Encoding: gzip");echo gzencode('songjiankang');

樣本1:

function ob_gzip ($content) // $content 就是要壓縮的頁面內容,或者說餅乾原料{    if (! headers_sent() &&     // 如果頁面頭部資訊還沒有輸出    extension_loaded("zlib") &&     // 而且zlib擴充已經載入到PHP中    strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip"))     // 而且瀏覽器說它可以接受GZIP的頁面    {        $content = gzencode($content . " \n//此頁已壓縮", 9); // 此頁已壓縮”的注釋標籤,然後用zlib提供的gzencode()函數執行層級為9的壓縮,這個參數值範圍是0-9,0表示無壓縮,9表示最大壓縮,當然壓縮程度越高越費CPU。                                                                          // 然後用header()函數給瀏覽器發送一些頭部資訊,告訴瀏覽器這個頁面已經用GZIP壓縮過了!        header("Content-Encoding: gzip");        header("Vary: Accept-Encoding");        header("Content-Length: " . strlen($content));    }    return $content; // 返回壓縮的內容,或者說把壓縮好的餅乾送回工作台。}ob_start('ob_gzip');

樣本2:

#ob_gzhandler 為php內建函數,具體參考手冊ob_start('ob_gzhandler');

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.