I’ve used 2 different methods of checking the url so far:
$h = @get_headers($url);
$status = array();
preg_match('/HTTP\/.* ([0-9]+) .*/', $h[0] , $status);
return ($status[1] == 200);
and
$file_headers = @get_headers($url);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
return $exists;
I’m just not sure how I can make these requests time out after a specified number of seconds. My script hangs for minutes, when a url doesn’t exist, before it finally comes back as offline status. Any ideas?
SOLUTION:
Used Curl to set the timeout using the following code:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
curl_close($curl);
preg_match("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches);
return ($matches[1] == 200);
You’ll have to roll your own
fsockopen()with URL handlers enabled, which lets you specify a timeout. But then you’re stuck building your own HTTP request from the ground up, so a better solution is to use curl. You can easily construct a head request in there, and specify a timeout with CURLOPT_CONNECTIMEOUT (for connecting) and CURLOPT_TIMEOUT (general overall timeout).