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 may not exist) using wget. If I try the download without being connected, wget proceeds to the next one thinking the file is not present.
The connection_status() function returns the current connection status. Possible values that can be returned are: 0 - CONNECTION_NORMAL - connection is running normally.
Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top. Windows 10 lets you quickly check your network connection status.
The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.
<?php
function is_connected()
{
$connected = @fsockopen("www.example.com", 80);
//website, port (try 80 or 443)
if ($connected){
$is_conn = true; //action when connected
fclose($connected);
}else{
$is_conn = false; //action in connection failure
}
return $is_conn;
}
?>
You can always ping good 'ol trusty google:
$response = null;
system("ping -c 1 google.com", $response);
if($response == 0)
{
// this means you are connected
}
This code was failing in laravel 4.2 php framework with an internal server 500 error:
<?php
function is_connected()
{
$connected = @fsockopen("www.some_domain.com", 80);
//website, port (try 80 or 443)
if ($connected){
$is_conn = true; //action when connected
fclose($connected);
}else{
$is_conn = false; //action in connection failure
}
return $is_conn;
}
?>
Which I didn't want to stress myself to figure that out, hence I tried this code and it worked for me:
function is_connected()
{
$connected = fopen("http://www.google.com:80/","r");
if($connected)
{
return true;
} else {
return false;
}
}
Please note that: This is based upon the assumption that the connection to google.com is less prone to failure.
The accepted answer did not work for me. When the internet was disconnected it threw a php error. So I used it with a little modification which is below:
if(!$sock = @fsockopen('www.google.com', 80))
{
echo 'Not Connected';
}
else
{
echo 'Connected';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With