How can error handling be improved in the provided PHP script to accurately determine the reachability of a website?
The issue with the provided PHP script is that it does not handle errors effectively when checking the reachability of a website. To improve error handling, we can use try-catch blocks to catch any exceptions that may occur during the connection attempt and provide appropriate error messages.
<?php
function isWebsiteReachable($url) {
try {
$headers = get_headers($url);
if ($headers && strpos($headers[0], '200') !== false) {
return true;
} else {
return false;
}
} catch (Exception $e) {
return false;
}
}
// Example usage
$url = 'https://www.example.com';
if (isWebsiteReachable($url)) {
echo 'Website is reachable.';
} else {
echo 'Website is not reachable.';
}
?>
Keywords
Related Questions
- How can the "s" modifier in preg_match_all affect the results of pattern matching in PHP?
- What is the recommended method for including text files based on URL variables in PHP?
- What are the common challenges faced when updating images in a PHP database, especially when dealing with multiple image uploads per entry?