Reputation: 3291
I'm using command-line PHP on linux to open bluetooth dialup connection, and I need a quick'n'dirty way to check if internet connection is active. Well, doesn't have to be dirty, but quick is appreciated. :) Using exec
to run external commands is not a problem.
I'm thinking of pinging some stable server (e.g. google), but I'm wondering if there's some better way. Maybe checking output of ifconfig
? A command that would respond with a clear response like ("cannot connect to server","connected") would naturally be best. Ideas?
Upvotes: 2
Views: 7513
Reputation: 99254
Internet connection? What's it? Please, define "internet connection"! You want to check whether the user is connected--to where? To your company's server? Well, ping it! Or to where? Aright, ping google.com, but with that you'll only check whether the user's connected to google's server, since all other sites may be banned by system administrator.
Generally, network routing is such a domain where you can't check whether you're connected to some kind of "Internet". You can only check particular servers.
Upvotes: 0
Reputation: 239041
If you want something that'll work without relying on an outside server, you can check for a default route. This command will print out the number of default routes:
/sbin/route -n | grep -c '^0\.0\.0\.0'
If it's 0
, you can't get to the outside world.
Upvotes: 11
Reputation: 6777
I suggest using ping too.. you could 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 decide to use wget, remember to prepend http:// to the url of the page you want to download, and i suggest adding "-q -O -" to the options to make wget not (try to) saving to file..
Another way to do that is by using curl/sockets on php, but i think it's not the quickest way you are looking for..
Upvotes: 3
Reputation: 116137
If you're comfortable with using exec, I would (to check your internet connection) ping your ISP's DNS servers (by IP)
exec("ping -c 1 $ip 2>&1", $output, $retval);
You could probably also do it in pure PHP by using fsockopen to try and fetch a page from www.google.com (the wget/curl 'scenario').
if(!fsockopen("www.google.com", 80)) {
echo "Could not open www.google.com, connection issues?";
}
Upvotes: 5
Reputation: 1118
You can use wget to some external web with timeout parameter -W for such thing. It returns 1 if timeout elapsed without success, and 0 if it gets within timeout. Also, ping can be used for such purpose, as you suggested.
Upvotes: 2