我想知道是否可以在 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 仅给出正文内容,而不给出包含身份验证令牌数据的标头。
函数 get_headers() 可能就是您正在寻找的函数。
您仍然可以使用方便的
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!