Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents: get full response even on error

Is it possible to make file_get_contents show me the actual response even if an error occurs?

It is difficult to debug otherwise. For instance, say you have the following code:

$url = 'https://api.twitter.com/oauth/request_token';
$data = array();

$options = array(
    'http' => array(
    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
    'method'  => 'POST',
    'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = @file_get_contents($url, false, $context);

var_dump($result);
var_dump($http_response_header);

This shows me NULL for the result and the HTTP headers, but I want to get the actual message Twitter sends back (should be something like Failed to validate oauth signature and token), which is what you get if you try to load https://api.twitter.com/oauth/request_token in your browser.

like image 454
houbysoft Avatar asked Aug 29 '13 14:08

houbysoft


1 Answers

There is a very simple switch for the context. just add this line to options:

'ignore_errors' => true

so you will get

$options = array(
    'http' => array(
    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
    'method'  => 'POST',
    'content' => http_build_query($data),
    'ignore_errors' => true
    )
);
like image 115
nvanesch Avatar answered Nov 15 '22 16:11

nvanesch