Irfan
Irfan

Reputation: 1768

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

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.

Upvotes: 3

Views: 14275

Answers (3)

L1Q
L1Q

Reputation: 15

You can still use the handy file_get_contents and have your headers via $http_response_header.

No need for fopen and stream_get_meta_data.

$http_response_header will be populated with response headers right in the scope where file_get_contents was called.

No need even to set ignore_errors as only the return value of file_get_contents is affected by failed request, $http_response_header will still have your HTTP 401s and 500s.

The code from the question would look like this:

$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!

Upvotes: 0

jason
jason

Reputation: 1255

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.

Upvotes: 2

Sinan
Sinan

Reputation: 5980

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

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

Upvotes: 1

Related Questions