PHP中POST请求后如何获取HTTP响应头?
我想知道在 PHP 中发出 POST 请求后是否可以在不使用 cURL 的情况下读取/解析 HTTP 响应标头。
我在 IIS7 下有 PHP 5 我用于 POST 的代码是:-
$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);
上面,我对 google 进行了简单的 ClientLogin 身份验证,我想获取在标头中返回的身份验证令牌。回显 $result 仅给出正文内容,而不给出包含身份验证令牌数据的标头。
I want to know if it's possible to read/parse the HTTP response header after a POST request in PHP without the use of cURL..
I have PHP 5 under IIS7
The code I use to POST is :-
$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);
Above, im doing a simple ClientLogin Authentication to google and I want to get the Auth token which returns in the header. Echo-ing $result only gives the body content and not headers which contains the auth token data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
ignore_errors
上下文选项(文档) :另外,也许使用
fopen
而不是file_get_contents
。然后,您可以调用stream_get_meta_data($fp)
来获取标头,请参阅上述链接上的示例#2。Use the
ignore_errors
context option (documentation):Also, maybe use
fopen
rather thanfile_get_contents
. You can then callstream_get_meta_data($fp)
to get the headers, see Example #2 on the above link.get_headers() 函数可能就是您正在寻找的函数。
http://php.net/manual/en/function.get-headers.php
The function get_headers() may be the one you are looking for.
http://php.net/manual/en/function.get-headers.php
您仍然可以使用方便的
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。
问题中的代码如下所示:
You can still use the handy
file_get_contents
and have your headers via $http_response_header.No need for
fopen
andstream_get_meta_data
.$http_response_header
will be populated with response headers right in the scope wherefile_get_contents
was called.No need even to set
ignore_errors
as only the return value offile_get_contents
is affected by failed request,$http_response_header
will still have yourHTTP 401
s and500
s.The code from the question would look like this: