0

I know this may have been asked before, but I can't find anything that quite matches my specific requirements.

I'm loading a page on a local Linux server, when it loads I need to know does the server it is running on have Internet Access and is DNS resolving.

I've got this working, BUT... if there is no Internet connection the page takes a very long time to load, if there is a connection then it loads instantly.

I'm using the following to check for Internet Access:

$check1 =  checkState('google-public-dns-a.google.com',53);
$check2 =  checkState('resolver1.opendns.com',53);
if ($check1 == "YES" || $check2 == "YES"){
    echo "Internet Available";
}


function checkState($site, $port) {
    $state = array("NO", "YES");
    $fp = @fsockopen($site, $port, $errno, $errstr, 2);
    if (!$fp) {
        return $state[0];
    } else  { 
        return $state[1];
    }
}

and checking DNS resolution using:

$nameToIP = gethostbyname('www.google.com');
if (preg_match('/^\d/', $nameToIP) === 1) {
   echo "DNS Resolves";
}

Can anyone recommend a better way ? so if there is no connection the page doesn't stall for a long time.

Thanks

Professor Abronsius
  • 26,348
  • 5
  • 26
  • 38
Rocket
  • 983
  • 2
  • 17
  • 33

1 Answers1

2

You can use fsockopen

Following example works well and tells you whether you are connected to internet or not

function is_connected() {
    $connected = @fsockopen("www.google.com", 80); //website, port  (try 80 or 443)                                      
    if ($connected){
       fclose($connected);       
       return true;
    }
    return false;
}

Reference : https://stackoverflow.com/a/4860432/2975952

Check DNS resolves here

function is_site_alive(){
    $response = null;
    system("ping -c 1 google.com", $response);
    if($response == 0){
       return true;
    }
    return false;
}

Reference : https://stackoverflow.com/a/4860429/2975952

Community
  • 1
  • 1
Thamaraiselvam
  • 6,391
  • 6
  • 39
  • 64
  • 1
    Why assign the boolean value to a `return`? Just `return`. if `if($connected){ fclose($connected); return true; //action when connected }else{ return false; //action in connection failure }` – ʰᵈˑ Oct 13 '16 at 08:00
  • 1
    Thanks is there anyway to check the Internet Access and DNS resolution separately ? – Rocket Oct 13 '16 at 08:03