What are some best practices for checking HTTP responses in PHP when using fsockopen and fgets?
When using fsockopen and fgets to make HTTP requests in PHP, it is important to check the HTTP response status code to ensure the request was successful. One common practice is to read the first line of the response, which contains the status code, and handle different status codes accordingly. This helps to catch errors or unexpected responses and take appropriate action in your code.
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if (!$fp) {
echo "Error: $errstr ($errno)\n";
} else {
$request = "GET / HTTP/1.1\r\n";
$request .= "Host: $host\r\n";
$request .= "Connection: close\r\n\r\n";
fwrite($fp, $request);
$response = "";
while (!feof($fp)) {
$response .= fgets($fp, 128);
// Check for end of HTTP headers
if (strpos($response, "\r\n\r\n") !== false) {
break;
}
}
list($httpVersion, $statusCode, $reasonPhrase) = explode(" ", strtok($response, "\r\n"));
if ($statusCode == 200) {
// Handle successful response
echo "Request was successful!";
} else {
// Handle other status codes
echo "Request failed with status code $statusCode";
}
fclose($fp);
}