Determine in php script if connected to internet?

<?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';
}

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.