Determine in php script if connected to internet?

2019-01-08 07:24发布

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.

10条回答
对你真心纯属浪费
2楼-- · 2019-01-08 07:56
/*
 * Usage: is_connected('www.google.com')
 */
function is_connected($addr)
  {
    if (!$socket = @fsockopen($addr, 80, $num, $error, 5)) {
      echo "OFF";
    } else {
      echo "ON";
    }
  }
查看更多
The star\"
3楼-- · 2019-01-08 07:57

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.

查看更多
\"骚年 ilove
4楼-- · 2019-01-08 08:07

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;
}
查看更多
做自己的国王
5楼-- · 2019-01-08 08:08

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.

查看更多
登录 后发表回答