hi,欢迎访问本站!
当前位置: 首页编程开发正文

php判断页面是否经过GZIP压缩

墨初 编程开发 304阅读

上篇博文说了一下在php中如何开启gzip压缩,那么这篇文章就说一下如何利用php脚本来判断网页是否已被GZIP压缩。

php检测网页是否经过gzip压缩

1、在php中使用curl扩展来检测网页是否gzip压缩

/**
 * @name 检测网页是否经过gzip压缩
 * @param string $url 需要检测的网址地址
 * 
 * @return bool true已压缩  false未压缩
 */
function IsGzip($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_ENCODING, ''); 
    $response = curl_exec($ch);
    if(!curl_errno($ch)){
        $info = curl_getinfo($ch);
        $header_size = $info['header_size'];
        $header_str = substr($response, 0, $header_size);
        $filter = array("\r\n", "\r");
        $header_str = str_replace($filter, PHP_EOL, $header_str);
        preg_match('/Content-Encoding: (.*)\s/i', $header_str, $matches);
        if(isset($matches[1]) && $matches[1]=='gzip'){
            return true;
        }
    }
    return false;
}

var_dump(IsGzip('https://www.73so.com'));

2、使用 get_headers 函数来检测网页是否gzip压缩

get_headers() 是php中的一个预设函数,它返回一个包含服务器响应一个 HTTP 请求所发送的标头的数组,我们可以检测数据中是否含有 Vary 元素,以及 Vary 元素的值是否为 Accept-Encoding ,来检测网页文件是否进行GZIP压缩。

/**
 * @name 检测网页是否经过gzip压缩
 * @param string $url 需要检测的网址地址
 * 
 * @return bool true已压缩  false未压缩
 * @host https://www.73so.com
 */
function IsGzip($url){
    $header = get_headers($url, 1);
    if(isset($header['Vary']) && $header['Vary'] == 'Accept-Encoding'){
        return true;
    }
    return false;
}

var_dump(IsGzip('https://www.73so.com'));
// bool(false)
声明:无特别说明,转载请标明本文来源!
相关推荐