[轉]PHP通過zlib擴充實現GZIP壓縮輸出

來源:互聯網
上載者:User

標籤:des   blog   http   java   使用   strong   

1. GZIP介紹

GZIP是GNU zip的縮寫,它是一個GNU自由軟體的檔案壓縮程式,也經常用來表示gzip這種檔案格式。GZIP主要用於Unix系統的檔案壓縮,我們經常看到的尾碼為.gz的檔案,它們就是GZIP格式的。GZIP的壓縮效果比較明顯,應用Gzip壓縮網頁時,網頁可以壓縮30%甚至更多。

HTTP協議上的GZIP編碼是一種用來改進WEB;應用程式效能的技術,Web開發中通過GZIP壓縮頁面來降低網站的流量,而且GZIP不會佔用很多CPU。總體來考慮,啟用GZIP還是非常划算的。通過HTTP頭,我們可以知道瀏覽器是否支援GZIP壓縮。一般是通過Accept-Encoding來查看,如果是:

Accept-Encoding:gzip,deflate,則表明支援mod_gzip和mod_deflate

2. Apache和 PHP開啟GZIP的方法

1) 更改Apache設定檔,支援mod_deflate模組

要Apache支援GZIP,Apache必須支援mod_deflate這個模組。修改Apache目錄下的設定檔httpd.conf,設定LoadModule deflate_module modules/mod_deflate.so

2)兩種開啟壓縮方式的介紹

伺服器預設不支援mod_gzip、mod_deflate模組,若想通過GZIP壓縮頁面內容,可以考慮兩種方式,開啟zlib.output_compression或者通過ob_gzhandler編碼的方式。

zlib.output_compression是在對網頁內容壓縮的同時發送資料至用戶端。

ob_gzhandler是等待網頁內容壓縮完畢後才進行發送,相比之下前者效率更高,但需要注意的是,兩者不能同時使用,只能選其一,否則將出現錯誤。

3) 啟用GZIP壓縮方法

方法一:修改Apache設定檔httpd.conf

修改Apache設定檔httpd.conf,在設定檔中添加如下代碼:

<IfModule mod_deflate.c>SetOutputFilter DEFLATEDeflateCompressionLevel 5AddOutputFilterByType DEFLATE text/html text/css image/gif image/jpeg image/png application/x-javascript</IfModule>

  

方法二:修改php 設定檔php.ini

zlib.output_compression = Off Off更改成On

zlib.output_compression_level = -1 zlib.output_compression_level 建議參數值是1~5,6以實際壓縮效果提升不大,cpu佔用卻是幾何增長。

方法三:通過.htaccess檔案開啟,伺服器必須開啟偽靜態

<IfModule mod_deflate.c>    # Insert filter on all content    SetOutputFilter DEFLATE    # Insert filter on selected content types only    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript    # Netscape 4.x has some problems...    BrowserMatch ^Mozilla/4 gzip-only-text/html    # Netscape 4.06-4.08 have some more problems    BrowserMatch ^Mozilla/4\.0[678] no-gzip    # MSIE masquerades as Netscape, but it is fine    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html    # Don‘t compress images    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary    # Make sure proxies don‘t deliver the wrong content    #Header append Vary User-Agent env=!dont-vary</IfModule>

  

方法四:通過ob_gzhandler編碼,在PHP頁面開啟

<?phpif(Extension_Loaded(‘zlib‘)) Ob_Start(‘ob_gzhandler‘); /*這裡為PHP頁面輸出內容*/if(Extension_Loaded(‘zlib‘)) Ob_End_Flush(); ?>

  

3. 檢測網站是否開啟GZIP

通過站長GZIP壓縮檢測功能

訪問 http://tool.chinaz.com/Gzips/,輸入網址,可以查看網站的是否啟用GZIP壓縮,網頁壓縮率等資訊

 

轉載自:http://www.phpmarker.com/187.html

聯繫我們

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