How to get HTTP response headers after POST request in PHP?

≯℡__Kan透↙ 提交于 2019-12-07 18:37:16

问题


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' => 'xxxxx@gmail.com',
        '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.


回答1:


The function get_headers() may be the one you are looking for.

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




回答2:


Use the ignore_errors context option (documentation):

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

Also, maybe use fopen rather than file_get_contents. You can then call stream_get_meta_data($fp) to get the headers, see Example #2 on the above link.



来源:https://stackoverflow.com/questions/6532753/how-to-get-http-response-headers-after-post-request-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!