How can PHP be used to detect and handle different HTTP status codes returned by a website?
To detect and handle different HTTP status codes returned by a website in PHP, you can use the cURL library to make HTTP requests and check the response code. You can then handle the different status codes accordingly in your PHP code.
$url = 'https://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status_code == 200) {
// Handle successful response
echo 'Success: ' . $response;
} elseif ($status_code == 404) {
// Handle not found error
echo 'Error 404: Page not found';
} else {
// Handle other status codes
echo 'Error: HTTP status code ' . $status_code;
}
curl_close($ch);