I use gravatar for images in my website, but if the network is bad, I would like to know that and use images in other ways. So how can I know if a particular website is not in service?
4 Answers
No need for complex socket and other remote processing. You can verify if the returned image is indeed an image using the PHP GD library:
if( !$size = getimagesize($filename) ) {
$image = 'images/default.jpg';
}

- 3,545
- 4
- 37
- 66
-
Always glad to help. Question upped and added to favorites ;) – Jhourlad Estrella Jun 03 '11 at 02:58
If your goal is simply to check whether a website is down, you can do this pretty simply in php as explained here and here. Essentially you will try to open that website and if something loads you assume its up and running, should it not load you assume the website is down.

- 3,234
- 4
- 24
- 37
Try this:
<?php
function GetServerStatus($site, $port)
{
$fp = @fsockopen($site, $port, $errno, $errstr, 2);
if (!$fp)
return false;
else
return true;
}
?>
pass it a site (or IP) and a port and it will return false if the site is down and true if the site is up. This will at least tell you if the site is down or not.

- 754
- 1
- 11
- 24
-
But may take some time to fail, depending on how the network is down. If you have no DNS resolution, it might be quick, but if you get an IP address the timeout might take a while to occur. – El Yobo Jun 03 '11 at 02:49
To know that a site is down, you basically need to try and get some data from it (webpage, image, whatever) and use a timeout. If no data is returned within that time period, assume it's down.
Here's a simple way:
<?php
ini_set('default_socket_timeout', 5);
function getNetworkStatus(url) {
return ( file_get_contents(urlencode($url)) !== false )
}
?>
The problem is you can't just keep querying the remote server, as this will add a big latency to your page/application - you will need to cache this information for a period of time (database, file, whatever).

- 4,442
- 2
- 22
- 25