如何在 PHP 中 POST 请求后获取 HTTP 响应头?

问题描述 投票:0回答:3

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

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

$url="http://www.google.com/accounts/ClientLogin";
$postdata = http_build_query(
    大批(
        '账户类型' => 'GOOGLE',
        '电子邮件' => '[电子邮件受保护]',
        '密码' => 'xxxxxx',
        '服务' => '融合表',
        '源' => '融合表查询'
    )
);
$opts = 数组('http' =>
    大批(
        'header' => '内容类型:application/x-www-form-urlencoded',
        '方法' => '发布',
        '内容' => $postdata
    )
);
$context =stream_context_create($opts);
$结果 = file_get_contents($url, false, $context);

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

php http-headers httpwebrequest
3个回答
2
投票

使用

ignore_errors
上下文选项(文档):

$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)
来获取标题,请参阅上面链接上的 示例 #2


1
投票

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

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


0
投票

您仍然可以使用方便的

file_get_contents
并通过 $http_response_header 获取标头。

不需要

fopen
stream_get_meta_data

$http_response_header
将在调用
file_get_contents
的范围内填充响应标头。

甚至不需要设置

ignore_errors
,因为只有
file_get_contents
的返回值会受到失败请求的影响,
$http_response_header
仍然会保留您的
HTTP 401
500

问题中的代码如下所示:

$url = "http://www.google.com/accounts/ClientLogin";
$postdata = http_build_query(
    array(
        'accountType' => 'GOOGLE',
        'Email' => '[email protected]',
        'Passwd' => 'xxxxxx',
        'service' => 'fusiontables',
        'source' => 'fusiontables query'
    )
);
$opts = array('http' =>
    array(
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'method'  => 'POST',
        'content' => $postdata
    )
);
$context  = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
$headers = $http_response_header; // this is all you have to do!
© www.soinside.com 2019 - 2024. All rights reserved.