Retrieving Response Codes in HTTP Requests Using file_get_contents
When making POST requests using file_get_contents with stream_context_create, users may encounter HTTP errors that generate warnings. To mitigate this and obtain the response code for error handling, follow these steps:
Suppress Error Warnings
Use the ignore_errors option in stream_context_create to suppress the warnings:
$context = stream_context_create(['http' => ['ignore_errors' => true]]);
Retrieve Response Code
The HTTP response code is stored in the $http_response_header PHP variable after executing file_get_contents. Use var_dump($http_response_header>) to view the headers, where the first element contains the response status (e.g., "HTTP/1.0 400 Bad Request").
Example
$context = stream_context_create(['http' => ['ignore_errors' => true]]); $result = file_get_contents("http://example.com", false, $context); var_dump($http_response_header); // Display response headers, including response code
The above is the detailed content of How to Retrieve HTTP Response Codes from `file_get_contents` POST Requests?. For more information, please follow other related articles on the PHP Chinese website!