HTTP Requests with file_get_contents: Retrieving Response Codes
When sending POST requests using file_get_contents and stream_context_create, error handling can be challenging. The code snippet provided demonstrates the basics of POST requests with file_get_contents, but it suffers from two limitations:
To address these limitations, consider the following solutions:
Suppressing Error Warnings
To suppress the unwanted warning, you can use the 'ignore_errors' option in the stream context:
$context = stream_context_create(['http' => ['ignore_errors' => true]]);
By enabling this option, file_get_contents will not display an error warning on HTTP errors and instead return a 'false' value, indicating a failed request.
Retrieving HTTP Response Codes
To obtain the HTTP response code, you can utilize the PHP superglobal variable $http_response_header, which becomes populated when using file_get_contents with a stream context. After you have suppressed the error warning, you can access the response code by using the following code:
$result = file_get_contents("http://example.com", false, $context); var_dump($http_response_header);
This will output the HTTP response headers, including the response code.
By implementing these solutions, you can enhance your code's ability to handle HTTP errors while making POST requests using file_get_contents and stream_context_create.
The above is the detailed content of How Can I Handle HTTP Errors and Retrieve Response Codes When Using `file_get_contents` for POST Requests?. For more information, please follow other related articles on the PHP Chinese website!