php 获取站点状态 - 向上或向下
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9817046/
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
Get the site status - up or down
提问by joHN
<?php
$host = 'http://google.com';
if($socket =@ fsockopen($host, 80, $errno, $errstr, 30)) {
echo 'online!';
fclose($socket);
} else {
echo 'offline.';
?>
I'm using the above program to get the status of site. But I always get an offline message. Is there any mistake with the code?
我正在使用上述程序来获取站点的状态。但我总是收到离线消息。代码有错误吗?
回答by Starx
What about a curl solution?
卷曲解决方案怎么样?
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"; }
回答by stewe
The hostname does not contain http://
, that is only the scheme for an URI.
主机名不包含http://
,这只是 URI 的方案。
Remove it and try this:
删除它并尝试这个:
<?php
$host = 'google.com';
if($socket =@ fsockopen($host, 80, $errno, $errstr, 30)) {
echo 'online!';
fclose($socket);
} else {
echo 'offline.';
}
?>
回答by OneHoopyFrood
I know this is an old post, but you could also parse the output of:
我知道这是一篇旧帖子,但您也可以解析以下输出:
$header_check = get_headers("http://www.google.com");
$response_code = $header_check[0];
That would give you the full HTTP status.
这将为您提供完整的 HTTP 状态。
回答by Rinku
This can work faster
这可以更快地工作
<?php
$domain = '5wic.com';
if(gethostbyname($domain) != $domain )
{
echo "Up";
}
else
{
echo "Down";
}
?>
回答by Rinku
should be
应该
if(fsockopen($host, 80, $errno, $errstr, 30)) {
...
not
不是
if($socket =@ fsockopen($host, 80, $errno, $errstr, 30)) {
...
but curl would be better
但卷曲会更好
回答by Mark Adewale
This is a quicker way than fsock.
这是比 fsock 更快的方法。
$url = 'https://google.com';
$url = gethostbyname(str_replace(['https://','http://'],NULL,$url));
if(filter_var($url,FILTER_VALIDATE_IP)) {
// online!
}
else {
// offline :(
}