View Full Version : Test if internet connection exists

03-22-2009, 05:13 PM
Hey everyone,

Well here I sit typing on a LAMP server that I use for a little bit of dev.

Some of my apps need the internet to communicate with other apps that I have written online.

The problem is that my internet comes and goes as it pleases.

Is there a way to quickly check if there is an internet connection, perhaps with a function that returns true or false?

I was looking at pinging with PHP but that looks WAAAAAY to complex for my uses.

Thanks a lot!

03-22-2009, 05:33 PM
It's not that hard to ping domain, add this function in your script or one of the include files:

function ping_domain($domain)
$file = @fsockopen ($domain, 80, $errno, $errstr, 10);

return (!$file) ? FALSE : TRUE;

Then to ping domain use

$domain = 'google.com';

if (ping_domain($domain))
echo "{$domain} is online.";
echo "{$domain} is offline.";

03-22-2009, 05:38 PM
Not sure you maybe could use file_get_contents("http://www.example.com");
that would return false if it cant connect to it for some reason. There's probably a better way around it tbh.

You could use

$str=exec("ping -c 1 -w 1",$a,$a1);

//not present


Not sure if this works i nicked it off of exec() (http://uk2.php.net/function.exec). And this is a windows PC so can't test it atm.

03-22-2009, 05:55 PM
Thanks steelaz, that works like a charm.

Tim, that code seems to say offline all the time. I didn't change the IP in the example you gave so that's probably why. Thanks anyway!

03-22-2009, 05:59 PM
lol it's probably for the best. steelaz method is far superior.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum