How can I check if I\'m connected to the internet from my PHP script which is running on my dev machine?
I run the script to download a set of files (which may or ma
/*
* Usage: is_connected('www.google.com')
*/
function is_connected($addr)
{
if (!$socket = @fsockopen($addr, 80, $num, $error, 5)) {
echo "OFF";
} else {
echo "ON";
}
}
Also note that fopen
and fsockopen
are different. fsockopen
opens a socket depending on the protocol prefix. fopen
opens a file or something else e.g file over HTTP, or a stream filter or something etc. Ultimately this affects the execution time.
Why don't you fetch the return code from wget to determine whether or not the download was successful? The list of possible values can be found at wget exit status.
On the other hand, you could use php's curl functions as well, then you can do all error tracking from within PHP.
There are various factors that determine internet connection. The interface state, for example. But, regardles of those, due to the nature of the net, proper configuration does not meen you have a working connection.
So the best way is to try to download a file that you’re certain that exists. If you succeed, you may follow to next steps. If not, retry once and then fail.
Try to pick one at the destination host. If it’s not possible, choose some major website like google or yahoo.
Finally, just try checking the error code returned by wget. I bet those are different for 404-s and timeouts. You can use third parameter in exec
call:
string exec ( string $command [, array &$output [, int &$return_var ]] )
This function handles what you need
function isConnected()
{
// use 80 for http or 443 for https protocol
$connected = @fsockopen("www.example.com", 80);
if ($connected){
fclose($connected);
return true;
}
return false;
}