3

How can I check if I'm connected to the internet from my PHP script which is running on my dev machine (not on a server somewhere)?

I run the script to download a set of files (which may or may not exist) using wget. If I try the wget download without being connected, wget proceeds to the next one thinking the file is not present, so I need to check before calling wget.

Steve
  • 1,857
  • 5
  • 32
  • 45
  • @Mark Baker - uh oh! Yes, that is mine - I didn't get a posting success on my first one and tried again after a while... please merge if you can! – Steve Feb 01 '11 at 09:49

2 Answers2

6

Just check if google.com is reachable:

<?php
if (!$sock = @fsockopen('www.google.com', 80, $num, $error, 5))
echo 'offline';
else
echo 'OK';
?>
woodleader
  • 923
  • 1
  • 5
  • 14
1

A quick check would be to do a hostname lookup for some domain.

<?php
$ip = gethostbyname('www.google.com');
if($ip != 'www.google.com') {
  //connected!
} else {
  //not connected
}
?>
mrbellek
  • 2,300
  • 16
  • 20
  • A DNS server on the local network will be usually functional even if the connection to the outside fails. As DNS query responses are cached, this may be returning an IP address for *hours* of offline state. – Piskvor left the building Feb 01 '11 at 09:03
  • Google has many rotating IP addresses for that single domain so I'm not sure if caching their IP is a good idea in the first place. – mrbellek Feb 01 '11 at 09:41
  • Well, it will serve the page from *any* of those IP addresses (it's not like only one of them is active at a time), so yes, it is a good idea. (if it wasn't, Google is free to set their authoritative nameservers to return DNS results with tiny TTLs) – Piskvor left the building Feb 01 '11 at 11:56