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

来自:互联网
时间:2019-10-03
阅读:

今天用工具检测网页是否经过GZIP压缩时,突然想到是否可以利用php代码来检测呢,查了查资料然后写了测试代码,竟然成功了。分享一下,看有人需要不。

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

php利用curl来检测网页是否经过GZIP压缩的方法

使用 php curl 来检查网页文件是否经过GZIP压缩,直接编写函数调用即可,简单方便

编写php函数

<?php
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("rn", "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;
}
?>

调用函数代码

<?php
$url = 'https://www.freexyz.cn';
if(IsGzip($url)){
    echo $url.' 经过GZIP压缩';
}else{
    echo $url.' 未经过GZIP压缩';
}
?>

输出结果:

https://www.freexyz.cn 经过GZIP压缩

php 利用 get_headers() 函数来检测网页是否经过GZIP压缩

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

编写php函数

<?php
function IsGzip($url){
    $header = get_headers($url, 1);
    if(isset($header['Vary']) && $header['Vary']=='Accept-Encoding'){
        return true;
    }
    return false;
}
?>

函数调用的方法

<?php
$url = 'https://www.bAIdu.com';
if(IsGzip($url)){
    echo $url.' 经过GZIP压缩';
}else{
    echo $url.' 未经过GZIP压缩';
}
?>

输出结果:

https://www.baidu.com 经过GZIP压缩

注:

关于 get_headers() 函数的使用,请查看本站的其它文章。

返回顶部
顶部