dongyoudi1342 2014-06-17 17:34
浏览 110

如何检查网站是否可访问?

I want to see if a website can be accessed or not with a PHP page.

Here is my plan:

<?php 
  $website = /* bool to see if site is up */
  if($website)
{
  echo'<iframe src="http://64.126.89.241/" width="100%" height="100%"/>';  
}else
{
  echo'<iframe src="http://tsiserver.us/backup/" width="100%" height="100%"/>';  
}
?>

The website will be hosted on another server, therefore if my internet goes down, a user may access the backup version of a site.

  • 写回答

3条回答 默认 最新

  • duan201444 2014-06-17 17:37
    关注

    Here is a simple function that will determine if a website exists using PHP and cURL

    function urlExists($url=NULL)  
    {  
        if($url == NULL) return false;  
        $ch = curl_init($url);  
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        $data = curl_exec($ch);  
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
        curl_close($ch);  
        if($httpcode>=200 && $httpcode<300){  
            return true;  
        } else {  
            return false;  
        }  
    }  
    

    This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.

    reference : https://stackoverflow.com/a/1239090/568414

    评论

报告相同问题?