php 获取标头响应代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3408049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting header response code
提问by Batfan
This is part of a PHP script I am putting together. Basically a domain ($domain1) is defined in a form and a different message is displayed, based on the response code from the server. However, I am having issues getting it to work. The 3 digit response code is all I am interested in.
这是我放在一起的 PHP 脚本的一部分。基本上,域 ($domain1) 在表单中定义,并根据来自服务器的响应代码显示不同的消息。但是,我在让它工作时遇到了问题。3 位数的响应代码是我唯一感兴趣的。
Here is what I have so far:
这是我到目前为止所拥有的:
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!";
}
}
}
回答by Mchl
$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!";
}
回答by Andres SK
If you have PHP 5.4.0+ you can use the http_response_code()function. Example:
如果你有 PHP 5.4.0+ 你可以使用 http_response_code ()函数。例子:
var_dump(http_response_code()); // int(200)
回答by christian Nguyen
Here is my solution for people who need send email when server down:
这是我为需要在服务器关闭时发送电子邮件的人提供的解决方案:
$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);
}
回答by RamaKrishna
You directly returned so function wont execute further foreach condition which you written. Its always better to maintain two functions.
您直接返回,因此函数不会进一步执行您编写的 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!";
}
}
}