ok i played around a bit with stream_set_timeout since the timeout in the fsockopen function only applies to connecting to the host and not reading and writing over a slow connection.
since it could possibly take 2 seconds to connect, and then another 3 for the timeout that leaves you at 5 seconds, so thats why in the stream_set_timeout i used a 2 instead of 3, just to reduce the time. but this works too.
<?php
$url = "http://www.zymic.com/images/ad.gif";
$parts = parse_url($url);
$fp = @fsockopen($parts['host'], 80, $errno, $errstr, 3);
if (!$fp) {
echo "down";
} else {
$req = "HEAD " . $parts['path'] . " HTTP/1.1\r\n"
."Host: " . $parts['host'] . "\r\n"
."Connection: Close\r\n\r\n";
fwrite($fp, $req);
stream_set_timeout($fp, 2);
$info = stream_get_meta_data($fp);
while (!feof($fp) && !$info['timed_out']) {
$info = stream_get_meta_data($fp);
$response .= fgets($fp);
}
$info = stream_get_meta_data($fp);
fclose($fp);
if (!$info['timed_out']) {
$lines = explode("\r\n", $response);
if (!preg_match("/HTTP\/1\.\d 2\d{2} OK/i", $lines[0])) {
echo "down";
} else {
echo "good";
}
} else {
echo "timed out";
}
}
?>