Retrieving HTTP Response Code with file_get_contents and stream_context_create
When utilizing file_get_contents and stream_context_create for POST requests, handling HTTP errors is crucial. By default, file_get_contents raises warnings when encountering HTTP errors, making it difficult to retrieve the response code.
To suppress these warnings and obtain the response code, you can leverage the following solution:
Suppressing Warnings and Retrieving Response Code
$options = [ 'http' => [ 'ignore_errors' => true ] ];
The 'ignore_errors' option suppresses warnings generated by file_get_contents.
$result = file_get_contents("http://example.com", false, $context);
var_dump($http_response_header);
This technique allows you to handle HTTP errors gracefully without warnings and retrieve the response code from the stream.
The above is the detailed content of How Can I Retrieve HTTP Response Codes Using `file_get_contents` and `stream_context_create`?. For more information, please follow other related articles on the PHP Chinese website!