Ignore http error code when using file_get_contents

Asked

Viewed 724 times

1

I’m using file_get_contents to make a request to a url. This request can return an error 422. When that mistake 422 is returned, I need to capture the body, which comes in format JSON. But the file_get_contents seems not to be able to return the content when the request returns an error code.

The returned message is as follows:

Failed to open stream: HTTP request failed! HTTP/1.1 422 Unprocessable Entity

When this Warning is generated, the file_get_contentsreturns FALSE, but I need it to return the content that is returned by the url, even if it has error code.

How do I make to file_get_contents ignore errors and return me the content?

For example (using the httpbin.org to return an error on purpose):

 file_get_contents('https://httpbin.org/status/422')
  • 1

    tries to manually set the Header to 200 : http_response_code(200)

  • This does not solve the problem, @Lucasqueirozribeiro. This changes the answer sent, not the one I receive in file_get_contents.

1 answer

1


The way found to solve this problem was by using a stream_context_create.

This function can create a context for the function file_get_contents and so we can configure it to not generate a Warning if there is a status code other than 200 in the request.

It is necessary to define a array with the value ignore_errors as TRUE, inside http.

Behold:

$context = stream_context_create([
    'http' => [
        'ignore_errors' => true,
        'method'        => $method,
        'header'        => $headers
    ]
]);

$response = file_get_contents('https://httpbin.org/status/422', false, $context);

With the above code, when the status is 422 (or any other error code), rather than file_get_contents return FALSE and shoot a Warning, it will return the content returned, idependent of the status code.

If you need to get some header value, you can use the special variable $http_response_header

Browser other questions tagged

You are not signed in. Login or sign up in order to post.