Determine in php script if connected to internet?

4.1k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

Just check if google.com is reachable:

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

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