2

I would like to check the internet connection status using php. I tried this:

<?php


    $connected = @fsockopen("www.google.com"); 
    if ($connected){
        $is_conn = true; //0
        fclose($connected);
    }else{
        $is_conn = false; //1
    }
    echo (int)$is_conn;



?>

but it always returns true if I'm connected to the internal notwork! I need it to return false if I'm not online even if I'm connected to internal network.

Shadin
  • 331
  • 1
  • 6
  • 14
  • What do you mean with internal network? Is there maybe a routing to the internet where you can access google? And you are running this on a local machine? And why are you disable error display with the @? – Maarkoize Dec 03 '13 at 10:41
  • No actually I cannot access google! I'm not sure why it returns true. and about disabling error I was testing something else sorry I forgot to remove it. – Shadin Dec 03 '13 at 11:00
  • 1
    What contains $errmsg when you change fsockopen() to fsockopen("www.google.com",80,$errnbr,$errmsg); – Maarkoize Dec 03 '13 at 11:03
  • Possible duplicate of [Determine in php script if connected to internet?](https://stackoverflow.com/questions/4860365/determine-in-php-script-if-connected-to-internet) – tgrrr Oct 10 '17 at 01:41

2 Answers2

4

Make use of this simple code to check whether internet is connected or not.

<?php
checkdnsrr('php.net') ? print 1: print 0; // " prints" 1 (If internet is ON)
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
2

when you use @fsockopen as offline

    if (!$sock = @fsockopen('www.google.com',80,$errorNum,$errorMessage)) {

    echo "no connection";
    echo $errorMessage;
}else{
    echo "connection";
    echo $errorMessage;

and print error message will be :

php_network_getaddresses: getaddrinfo failed: System error
ahmed hamdy
  • 5,096
  • 1
  • 47
  • 58