[英]continuously loading if there is no internet connection
我目前正在開發一個在線控制的房屋,但是互聯網連接檢查器存在問題。
我有這段代碼來檢測是否有互聯網連接或沒有互聯網連接。
$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"}]';
}
?>
功能上的微小變化也許可以啟發這種情況。 例如:
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
。 當然,這並不意味着您沒有Internet連接,但是您在指定端口到達的主機不會回復。 無論如何,它只會使函數失敗並返回錯誤消息。 另外,請務必注意fsocopen
中3秒的timeout
限制,因為您可以根據需要進行更改。
編輯
一種更簡單,也許更准確的方法可以解決您的問題。
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');
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.