How can PHP be used to check if a website is reachable before displaying it in an iframe?

When displaying a website in an iframe using PHP, it's important to first check if the website is reachable to avoid potential errors or security risks. This can be done by sending a HTTP request to the website and checking the response code. If the response code is in the 2xx range, then the website is reachable and can be safely displayed in the iframe.

$url = 'https://www.example.com';
$headers = @get_headers($url);
if(strpos($headers[0], '200') !== false){
    echo '<iframe src="' . $url . '"></iframe>';
} else {
    echo 'Website is not reachable.';
}