2010-08-04 67 views
5

这是我放在一起的PHP脚本的一部分。基本上,域($ domain1)在表单中定义,并根据服务器的响应代码显示不同的消息。但是,我遇到问题需要解决。 3位响应代码都是我感兴趣的获取标题响应代码

这是我到目前为止有:。

function get_http_response_code($domain1) { 
    $headers = get_headers($domain1); 
    return substr($headers[0], 9, 3); 
    foreach ($get_http_response_code as $gethead) { 
     if ($gethead == 200) { 
      echo "OKAY!"; 
     } else { 
      echo "Nokay!"; 
     } 
    } 
} 
+0

看起来你在那里有一些有趣的缩进/大括号。 – Zaz 2010-08-04 17:29:19

+0

你有什么问题?请粘贴您收到的任何相关错误。另外,假设你粘贴的代码准确地反映了你的脚本,那么你的'return'语句下面的代码都不会执行。 – 2010-08-04 17:30:22

回答

14
$domain1 = 'http://google.com'; 

function get_http_response_code($domain1) { 
    $headers = get_headers($domain1); 
    return substr($headers[0], 9, 3); 
} 

$get_http_response_code = get_http_response_code($domain1); 

if ($get_http_response_code == 200) { 
    echo "OKAY!"; 
} else { 
    echo "Nokay!"; 
} 
+0

很好,谢谢:) – Batfan 2010-08-04 18:32:58

+0

工作对于大多数事情,但是如果网站发送重定向,那么重定向代码是第一个,即'$ headers [0] = 301; $ headers [5] = 404'这可能意味着它工作或不工作。 – mt025 2017-12-01 01:27:45

6

如果你有PHP 5.4.0+您可以使用http_response_code()功能。例如:

var_dump(http_response_code()); // int(200) 
+0

不知道为什么你回答2年的问题(这是2年前回答),但是,感谢信息:) – Batfan 2013-06-03 16:44:46

+3

哦,我正在寻找一个http响应代码相关的解决方案,并打开此线程。我发布这个以防有人在这里以某种方式到达。最好的祝福! – andufo 2013-06-03 17:22:47

+2

'http_response_code()'用于设置传出代码(例如浏览器),不检查传入代码(来自服务器),这是OP想要做的事情。 – 2014-10-25 00:43:31

0

这里是我的谁需要发送电子邮件时关闭服务器的人的解决方案:

$url = 'http://www.example.com'; 

while(true) { 

    $strHeader = get_headers($url)[0]; 

    $statusCode = substr($strHeader, 9, 3); 

    if($statusCode != 200) { 
     echo 'Server down.'; 
     // Send email 
    } 
    else { 
     echo 'oK'; 
    } 

    sleep(30); 
} 
0

你直接返回所以功能不会执行你写的foreach进一步情况。它总是更好地保持两个功能。

function get_http_response_code($domain1) { 
    $headers = get_headers($domain1); 
    return substr($headers[0], 9, 3); //**Here you should not return** 
    foreach ($get_http_response_code as $gethead) { 
     if ($gethead == 200) { 
      echo "OKAY!"; 
     } else { 
      echo "Nokay!"; 
     } 
    } 
}