如果没有互联网连接,则连续加载

时间:2018-06-16 10:08:15

标签: php apache raspberry-pi raspberry-pi3

我目前正在开发一个在线控制的家庭,但我的互联网连接检查器有问题。

我有这段代码来检测是否有互联网连接或没有互联网连接。

$check = @fsockopen("www.google.com", 80); 
if($check){
    return true;
    fclose($check);
}else{
     return false;
     fclose($check);
}

但问题是,当我的Raspberry Pi没有互联网连接时,它会不断加载页面。

完整的脚本在这里

<?php
    function checkConnection(){
        $check = @fsockopen("www.google.com", 80); 
        if($check){
            return true;
            fclose($check);
        }else{
             return false;
             fclose($check);
        }
    }
    if(checkConnection()==true){
        echo '[{"status":"success","result":"Internet Connection is Available"}]';
    }else{
        echo '[{"status":"fail","result":"No Internet Connection"}]';
    }
?>

2 个答案:

答案 0 :(得分:0)

也许你的功能上的一个小改变可能会启发这种情况。例如:

   function checkConnection() {
         $fp = @fsockopen("www.google.com", 80, $errno, $errstr, 3); 
         if (!$fp) {
             return "$errstr ($errno)<br />\n";
         } else {
             return true;
         }
    }
    $con = checkConnection();
    if ($con===true) {
        echo json_encode( ["status" => "success","result" => "Internet Connection is Available"] );
    } else {
        //  should not be - No Internet Connection is Available
        echo json_encode( ["status" => "fail","result" => $con] );
    }
  

PS:在PHPFiddle中试用,并确保将端口从80更改为83。这当然并不意味着您没有互联网连接,而是您在指定端口到达的主机没有回复。无论如何,它只会使函数失败并返回错误消息。另请注意timeout中的fsocopen限制为3秒,因为您可以根据需要对其进行更改。

修改

对于你想要做的事情,一个更简单,也许更准确的方法可能是这个。

   function checkConnection($hostname) {           
         $fp = gethostbyname($hostname);
         if (!inet_pton($fp)) {
            return json_encode( ["status" => "fail","result" => "Internet Connection is not Available or Host {$hostname} is wrong or does not exist."] ); 
         } else {
            return json_encode( ["status" => "success","result" => "Internet Connection is Available. Host {$hostname} exists and resolves to {$fp}"] );
         }
    }
    echo checkConnection('www.google.com');
  

您可能需要检查此comment in php.net,为gethostbyname设置替代选项。

答案 1 :(得分:0)

fsockopen将超时作为最后一个参数,仅在连接套接字时适用

DNS查找也是一个因素,AFAIK你无法控制超时,除非你在那种情况下使用gethostbyname()就可以使用

putenv('RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1');

将DNS查询限制为 1s

根据您的代码,我将如何实现它。

function is_connected()
{
    //1. provide a timeout to your socket
    //2. use example.com as a domain, that's what it's made for (testing)
    $socket = @fsockopen("www.example.com", 80, $err_no, $err_str, 5);
    if ($socket){
        fclose($socket);
        return true; 
    }
    return false;
}

$success = json_encode(["status" => "success","result" => "Internet is Available"]);
$failure = json_encode(["status" => "fail","result" => "Internet is Unavailable"]);

echo is_connected() ? $success : $failure;