Reputation: 190
I am using phps file_get_contents
to connect with my API server. It works well when the server returns with 200 status (it return the content from the api server). The problem is when the api server returns with 400 status. If the api server returns with 400 status the function simply returns FALSE (not the content).
here is what I get from $http_response_header
[ "HTTP\/1.1 400 Bad Request",
"Server: nginx\/1.16.1",
"Date: Fri, 06 Nov 2020 05:39:09 GMT",
"Content-Type: application\/json",
"Content-Length: 117",
"Connection: close",
"Strict-Transport-Security: max-age=31536000; includeSubDomains; preload",
"Access-Control-Allow-Origin: *",
"Access-Control-Expose-Headers: Content-Length,Content-Type,Date,Server,Connection" ]
Now my question is how can I get the content sent fron the API server when the status is 400?
Upvotes: 2
Views: 39
Reputation: 146460
You just need to enable the ignore_errors flag:
$context = stream_context_create([
'http' => [
'ignore_errors' => true,
],
]);
var_dump(file_get_contents('http://example.com/', false, $context));
Upvotes: 1
Reputation: 9469
You can rather use curl than file_get_contents
as this one has better support for error handling:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "{url}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
// handle any other code than 200
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
// your handling code
print_r($output);
}
curl_close($ch);
Upvotes: 1