PHP 8.5.0 Alpha 2 available for testing

Voting

: seven plus two?
(Example: nine)

The Note You're Voting On

blazely at removetoemail netspace net au
22 years ago
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) // Check the status of the link
{
$endHeader = false; // Strip initial header information
while ( !$endHeader)
{
if (
fgets($urlHandle) == "\r\n")
$endHeader = true;
}

return
$urlHandle; // All OK, return the file handle
}
else if (
strlen($response) < 15) // Cope with wierd non standard responses
{
fclose($urlHandle);
return -
1;
}
else
// Cope with a standard error response
{
fclose($urlHandle);
return
substr($response,9,3);
}
}

return
$urlHandle;
}
else
{
return
0;
}
}
}
?>

<< Back to user notes page

To Top