获取站点状态 - 向上或向下

时间:2012-03-22 05:41:08

标签: php web

<?php
$host = 'http://google.com';
if($socket =@ fsockopen($host, 80, $errno, $errstr, 30)) {
echo 'online!';
fclose($socket);
} else {
echo 'offline.';
?>

我正在使用上述程序来获取网站的状态。但我总是得到一个离线消息。 代码有什么错误吗?

7 个答案:

答案 0 :(得分:23)

卷曲解决方案怎么样?

function checkOnline($domain) {
   $curlInit = curl_init($domain);
   curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
   curl_setopt($curlInit,CURLOPT_HEADER,true);
   curl_setopt($curlInit,CURLOPT_NOBODY,true);
   curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);

   //get answer
   $response = curl_exec($curlInit);

   curl_close($curlInit);
   if ($response) return true;
   return false;
}
if(checkOnline('http://google.com')) { echo "yes"; }

答案 1 :(得分:18)

主机名不包含http://,这只是URI的方案。

删除它并尝试:

<?php
$host = 'google.com';
if($socket =@ fsockopen($host, 80, $errno, $errstr, 30)) {
echo 'online!';
fclose($socket);
} else {
echo 'offline.';
}
?>

答案 2 :(得分:4)

我知道这是一篇旧帖子,但您也可以解析输出:

$header_check = get_headers("http://www.google.com");
$response_code = $header_check[0];

这将为您提供完整的HTTP状态。

答案 3 :(得分:3)

这可以更快地运作

<?php
$domain = '5wic.com';
if(gethostbyname($domain) != $domain )
{
echo "Up";
}
else
{
echo "Down";
}
?>

答案 4 :(得分:1)

应该是

if(fsockopen($host, 80, $errno, $errstr, 30)) {
...

if($socket =@ fsockopen($host, 80, $errno, $errstr, 30)) {
...

但是卷曲会更好

答案 5 :(得分:0)

这是比fsock更快的方法。

$url = 'https://google.com';
$url = gethostbyname(str_replace(['https://','http://'],NULL,$url));
if(filter_var($url,FILTER_VALIDATE_IP)) {
   // online!
}
else {
   // offline :(
}

答案 6 :(得分:0)

您可以使用此:

function is_on($domain) {
  if(gethostbyname($domain) === gethostbyname("testillegaldomain.tld")) {
    return false;
  } else {
    return true;
  }
}

这将获取一个不存在的域的IP地址,并将其与您域的IP进行比较;如果相等,则表示站点已关闭,否则处于打开状态。

此外,使用此功能时请勿包含https://前缀!