【问题标题】:How to detect file_get_contents is returning gzipped content如何检测 file_get_contents 正在返回 gzip 压缩的内容
【发布时间】:2018-10-22 02:12:24
【问题描述】:

我正在使用以下内容获取我网站上视频的网址。

$vid = 231231; 
$url = file_get_contents("https://www.thevideositeurl.com/embed/{$vid}/") 
echo $url ; 

请注意:$vid 变量是动态的,有时它会返回 gziped 内容。

我已经知道我可以使用gzdecode 函数来解压缩该内容,如下所示:

$vid = 231231; 
$url = file_get_contents("https://www.thevideositeurl.com/embed/{$vid}/") 
$decodeit = gzdecode($url);
echo $decodeit; 

现在,问题是我需要找到一种方法来解码$url 变量,只有在需要时。 “需要”是指:如果 ($url) 它返回 gziped 内容,因为我需要对同一源使用相同的代码。

这里可以做一些检查吗?怎么样?

【问题讨论】:

  • 检查前两个字节?你看过 gzip 文件格式吗?

标签: php http-headers gzip


【解决方案1】:

您可以查看$http_response_header中的Content-Type或Content-Encoding。

【讨论】:

  • 在这种情况下我该怎么做(检查$url 是否返回压缩内容)?
  • @Alex 在他的回答中链接的文章 Kjartan 中对此进行了解释。 $http_response_headerfile_get_contents 函数定义,您可以循环遍历它包含的数组以查找返回的内容类型。
【解决方案2】:

调用file_get_contents后,$http_response_header会返回响应头,包括状态码。

Content-Encoding 标头指定使用哪种编码,例如标头Content-Encoding: gzip 将指定内容使用gzip 编码。

所以我会编写一个函数将标头映射到数组header name => value,然后检查Content-Encoding 条目以确定响应是否使用gzip 压缩。

创建从标题名称到值的映射

function transformIntoHeaderMap(array $headers)
{

去掉状态标头(例如HTTP/1.1 200 OK),因为它不适合header name: value 格式。

    $headersWithValues = array_filter($headers, function ($header) { return strpos($header, ':') !== false; });

现在在: 处拆分标题并将键和值写入映射。修剪值,以消除开头/结尾处的空格。

    $headerMap = [];
    foreach ($headersWithValues as $header) {
            list($key, $value) = explode(':', $header);
            $headerMap[$key] = trim($value);
    }

    return $headerMap;
}

判断内容是否被压缩

检查header是否设置,然后检查是否有你要找的值(gzip)。

function isGzipHeaderSet(array $headerMap)
{
    return isset($headerMap['Content-Encoding']) && 
        $headerMap['Content-Encoding'] == 'gzip';
}

解压缩内容(如果已压缩)

$vid = 231231; 
$contents = file_get_contents("https://www.thevideositeurl.com/embed/{$vid}/");
if (isGzipHeaderSet(transformIntoHeaderMap($http_response_header))) {
    $contents = gzdecode($contents);
}

echo $contents;

替代方案

更简单的方法可能是使用array_search 并直接在$http_response_header 中查找字符串Content-Encoding: gzip。但我认为这种方法对于标题中的空格更加健壮。

【讨论】:

    【解决方案3】:

    在某些情况下可以使用 HTTP 请求标头。

     $httpHeaders = array(
            "header" =>
                array("Accept-Encoding: identity")
            );
    
      $context = stream_context_create(array('http' => $httpHeaders));
    
    
      $response = file_get_contents("https://www.thevideositeurl.com/embed/{$vid}/", false, $context );
    

    Encoding标头中的identity值表示应该不加修改地返回内容,可以read more here。这意味着不应以任何方式对其进行压缩。

    在执行此操作之前请考虑响应的大小,因为您可能会增加端点提供商使用的带宽量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多