【问题标题】:How to get HTTP response headers after POST request in PHP?如何在 PHP 中的 POST 请求后获取 HTTP 响应标头?
【发布时间】:2011-09-25 20:10:48
【问题描述】:

我想知道是否可以在不使用 cURL 的情况下在 PHP 中的 POST 请求之后读取/解析 HTTP 响应标头。

我在 IIS7 下有 PHP 5 我用来发布的代码是:-

$url="http://www.google.com/accounts/ClientLogin"; $postdata = http_build_query( 大批( 'accountType' => 'GOOGLE', '电子邮件' => 'xxxxx@gmail.com', '密码' => 'xxxxxx', '服务' => 'fusiontables', 'source' => 'fusiontables 查询' ) ); $opts = 数组('http' => 大批( 'header' => '内容类型:应用程序/x-www-form-urlencoded', '方法' => 'POST', '内容' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents($url, false, $context);

上面,我正在对谷歌进行简单的 ClientLogin 身份验证,我想获取在标题中返回的身份验证令牌。回显 $result 仅给出正文内容,而不给出包含身份验证令牌数据的标题。

【问题讨论】:

  • 不要认为您的示例中可以包含响应标头(file_get_contents 将返回响应正文)
  • 那么php5中的get_headers()是做什么的呢? (思南在下面回答)或者您是否推荐使用 php5 从 Google ClienLogin 获取身份验证令牌的任何解决方法?

标签: php http-headers httpwebrequest


【解决方案1】:

函数 get_headers() 可能是您正在寻找的那个。

http://php.net/manual/en/function.get-headers.php

【讨论】:

  • hmm 很奇怪,但现在我得到:“无法打开流:无法找到套接字传输“ssl” - 您在配置 PHP 时是否忘记启用它?”但我没有使用 https?!
  • @Power-Inside,您可能被重定向到 SSL URL。请参阅http context documentation 中的follow_locationmax_redirects 选项。
【解决方案2】:

使用 ignore_errors 上下文选项 (documentation):

$opts = array('http' =>
    array(
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'method'  => 'POST',
        'content' => $postdata,
        'ignore_errors' => true,
    )
);

另外,也许使用fopen 而不是file_get_contents。然后您可以调用stream_get_meta_data($fp) 来获取标题,请参阅上面链接中的Example #2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2021-07-08
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多