Home >Backend Development >PHP Tutorial >How Can I Retrieve HTTP Response Codes Using `file_get_contents`?
Getting the HTTP Response Code from HTTP Requests Using file_get_contents
When utilizing file_get_contents for POST requests with stream_context_create, you may encounter HTTP errors and warnings. This article explores methods to handle these errors effectively.
To suppress the warning, you can set the 'ignore_errors' key to true within the 'http' options array of stream_context_create, as seen below:
$context = stream_context_create(['http' => ['ignore_errors' => true]]); $result = file_get_contents("http://example.com", false, $context);
This eliminates the warnings and allows you to proceed with your own exception handling logic.
To retrieve the response code, you can utilize the $http_response_header variable, which is populates with the response headers upon execution of file_get_contents:
var_dump($http_response_header);
By accessing this variable, you can obtain detailed information about the HTTP response, including the response code and other headers.
The above is the detailed content of How Can I Retrieve HTTP Response Codes Using `file_get_contents`?. For more information, please follow other related articles on the PHP Chinese website!