php檢測url頁面是否使用gzip壓縮小結

來源:互聯網
上載者:User

如果開啟gzip壓縮傳輸呢

apache

第1步

 代碼如下 複製代碼

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

然後在http.conf加如下例代碼

 代碼如下 複製代碼

# BEGIN GZIP
#apache開啟gzip壓縮,前提要裝gzip模組哦
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html
text/plain text/xml text/css application/x-javascript
application/javascript
</ifmodule>
# END GZIP

如果你是nginx伺服器也可參考下面代碼

 代碼如下 複製代碼

#nginx開啟gzip壓縮,放在location內
gzip on;
gzip_min_length 1000;
gzip_buffers 4 8k;
gzip_http_version 1.1;
gzip_types text/text text/html text/plain text/xml
 text/css application/x-javascript application/javascript;

現在重啟一下apache或nginx 即可,那麼要如何檢查是否正確開啟gzip呢,我們可使用下面php代碼

 

 代碼如下 複製代碼

//米爾軍事網採用 gzip壓縮網頁
//file_get_contents 直接獲得的網頁是亂碼。
header('Content-Type:text/html;charset=utf-8' );
$url = 'http://www.111cn.net';
$file = fopen($url, "rb");  
//唯讀2位元組  如果為(16進位)1f 8b (10進位)31 139則開啟了gzip ;
$bin = fread($file, 2); 
fclose($file);  
$strInfo = @unpack("C2chars", $bin);  
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);  
$isGzip = 0;  
switch ($typeCode)  
{
    case 31139:      
      //網站開啟了gzip
        $isGzip = 1;
        break;
    default:  
        $isGzip = 0;
}  
$url = $isGzip ? "compress.zlib://".$url:$url; // 三元運算式
$mierHtml = file_get_contents($url); //獲得米爾軍事網資料
$mierHtml = iconv("gbk","utf-8",$mierHtml);
echo $mierHtml;

例2

 代碼如下 複製代碼

<?php
/*
php 判斷url頁面是否使用gzip壓縮
*/
$ch = curl_init("http://www.111cn.net/");//url不能有轉向
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip, deflate'));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$buffer = curl_exec($ch);
$curl_info = curl_getinfo($ch);
curl_close($ch);
$header_size = $curl_info["header_size"];
//頭部資訊長度
$headers = substr($buffer, 0, $header_size);
//擷取頭部資訊
$body = substr($buffer, $header_size);
//擷取網頁內容
 
function getEncoding(&$headers){
    $arr=explode("rn",trim($headers));
    array_shift($arr);
    foreach($arr as $header){
        list($k,$v)=explode(':',$header);
        if ('content-encoding'==strtolower($k)){
            return trim($v);
        }
    }
    return false;
}   
 
$encoding=getEncoding($headers);
 
if ($encoding) {
    echo "Using: ".$encoding;
}else{
    echo "None";
}
 
?>
 

聯繫我們

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