Rocket
Rocket

Reputation: 1093

php - check internet connect and DNS resolution

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

Upvotes: 0

Views: 2562

Answers (1)

Thamaraiselvam
Thamaraiselvam

Reputation: 7080

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

Upvotes: 2

Related Questions