Checking internet connection using PHP command line on Linux

I am using a PHP interface from the command line to open a bluetooth connection and I need a quick 'dirty' way to check if the internet connection is active. Well, it doesn't have to be messy, but it is quickly appreciated. :) Using exec

external commands to run is not a problem.

I am thinking about checking out some stable server (like google), but I am wondering if there is any better way. Maybe checking the output ifconfig

? Naturally, a command that responds with a clear answer like ("cannot connect to the server", "connected") will be better. Ideas?

+2


source to share


5 answers


If you want something that will work without relying on an external server, you can check the default route. This command will print the number of default routes:

/sbin/route -n | grep -c '^0\.0\.0\.0'

      



If he is 0

, you cannot get to the outside world.

+10


source


If you are comfortable with exec I would (check your internet connection) ping your ISP DNS servers (by IP)

exec("ping -c 1 $ip 2>&1", $output, $retval);

      



Perhaps you can also do this in pure PHP using fsockopen to try and find the page from www.google.com (wget / curl ').

if(!fsockopen("www.google.com", 80)) {
    echo "Could not open www.google.com, connection issues?";
}  

      

+5


source


I suggest using ping too .. you can use something like:

exec("ping -c 4 www.google.com", $output, $status);
if ($status == 0) {
  // ping succeeded, we have connection working
} else {
  // ping failed, no connection
}

      

If you choose to use wget, remember to add http: // to the URL of the page you want to download, and I suggest adding "-q -O -" to the make options wget not (try) save to file.

Another way to do this is using curl / sockets in php, but I think this is not the fastest way you are looking for.

+3


source


You can use wget on some external network with the -W timeout option for such a thing. It returns 1 if the timeout passed without success, and 0 if it hits within the timeout. Also, ping can be used for this purpose, as you intended.

+2


source


Internet connection? What is it? Please define "internet connection"! Do you want to check if a user is connected - where? To your company's server? Well, ping! Or where? Aright, ping google.com, but with this, you will only check if the user is connected to the google server, since all other sites can be blocked by the system administrator.

Typically, network routing is a domain where you cannot check if you are connected to some kind of "Internet". You can only check specific servers.

0


source







All Articles