Here's a quick function to establish a connection to a web server that will time out if the connection is lost after a user definable amount of time or if the server can't be reached.
Also supports Basic authentication if a username/password is specified. Any improvements or criticisms, please email me! :-)
Returns either a resource ID, an error code or 0 if the server can't be reached at all. Returns -1 in the event that something really wierd happens like a non-standard http response or something. Hope it helps someone.
Cheers,
Ben Blazely
<?php
function connectToURL($addr, $port, $path, $user="", $pass="", $timeout="30")
{
$urlHandle = fsockopen($addr, $port, $errno, $errstr, $timeout);
if ($urlHandle)
{
socket_set_timeout($urlHandle, $timeout);
if ($path)
{
$urlString = "GET $path HTTP/1.0\r\nHost: $addr\r\nConnection: Keep-Alive\r\nUser-Agent: MyURLGrabber\r\n";
if ($user)
$urlString .= "Authorization: Basic ".base64_encode("$user:$pass")."\r\n";
$urlString .= "\r\n";
fputs($urlHandle, $urlString);
$response = fgets($urlHandle);
if (substr_count($response, "200 OK") > 0) {
$endHeader = false; while ( !$endHeader)
{
if (fgets($urlHandle) == "\r\n")
$endHeader = true;
}
return $urlHandle; }
else if (strlen($response) < 15) {
fclose($urlHandle);
return -1;
}
else {
fclose($urlHandle);
return substr($response,9,3);
}
}
return $urlHandle;
}
else
{
return 0;
}
}
}
?>