【问题标题】:How to analyze headers in PHP如何在 PHP 中分析标头
【发布时间】:2011-06-20 23:50:32
【问题描述】:

我正在使用 file_get_contents 与 api 交互以处理简单的 GET 请求……但有时它会抛出标头,表示出现错误。如何获取这些标头并确定是否存在问题?

【问题讨论】:

    标签: php api curl header


    【解决方案1】:

    使用 curl 代替 file_get_contents。

    见:http://www.php.net/manual/en/curl.examples-basic.php

    我想如果您与 REST Api 通信,那么您实际上希望返回 Http 状态代码。在这种情况下,您可以这样做:

    <?php
    $ch = curl_init("http://www.example.com/api/users/1");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 501) {
        echo 'Ops it not implemented';
    }
    fclose($fp);
    ?>
    

    【讨论】:

    • +1。此外,file_get_contents 并不总是适用于 web url,具体取决于服务器配置。
    【解决方案2】:

    Php 将在file_get_contents 之后设置 $http_response_header,其中包含响应标头作为标头行/字符串的数组。如果您想要的只是标题响应,则没有必要使用 curl(可能不应该,一些 LAMP 堆栈仍然没有 cURL)。

    关于 $http_response_header 的文档: http://php.net/manual/en/reserved.variables.httpresponseheader.php

    示例:

    file_get_contents('http://stacksocks.com');
    
    foreach ($http_response_header as $header)
    {
        echo $header . "<br>\n";
    }
    

    取自 cmets 帖子的提示:

    1) 值随每个请求而变化 制作。

    2) 在方法/函数中使用时, 当前值必须传递给 方法/功能。使用 $http_response_header 直接在 方法/功能没有被分配 函数/方法参数的值 将导致错误消息: 注意:未定义的变量: http_response_header

    3) 数组长度和值 数组中的位置可能会改变 取决于被查询的服务器 以及收到的回复。我不是 确定是否有任何“绝对”价值 数组中的位置。

    4) $http_response_header 仅获取 使用 file_get_contents() 填充 使用 URL 而不是本地文件时。 这在描述中说明时 它提到了 HTTP_wrapper。

    【讨论】:

    【解决方案3】:
    file_get_contents('http://example.com');
    var_dump($http_response_header);
    

    【讨论】:

      猜你喜欢
      • 2011-01-13
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 2017-10-08
      相关资源
      最近更新 更多