Ignore http error code when using file_get_contents

1

I'm using file_get_contents to make a request to a url. This request may return a 422 error. When this 422 error is returned, I need to capture the body, which comes in JSON format. However, file_get_contents does not seem to be able to return content when the request returns an error code.

The message returned is as follows:

  

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

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

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

For example (using link to return an error on purpose):

 file_get_contents('https://httpbin.org/status/422')
    
asked by anonymous 29.11.2016 / 20:19

1 answer

1

The way to solve this problem was to use stream_context_create .

This function can create a context for the file_get_contents function and so we can set it to not generate a warning in case of a status code other than 200 in the request. >

It is necessary to set a array with the value ignore_errors as TRUE , within http .

See:

$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 code above, when the status is 422 (or any other error code), instead of file_get_contents return FALSE and fire a Warning , it will return to content returned, depending on the status code.

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

    
11.01.2017 / 16:08