Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

php - 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
",
    '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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
",
    'method'  => 'POST',
    'content' => http_build_query($data),
    'ignore_errors' => true
    )
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...