note 32830 added to function.fsockopen

From: Date: Sun, 08 Jun 2003 14:55:23 +0000
Subject: note 32830 added to function.fsockopen
Groups: php.notes 
Request: Send a blank email to php-notes+get-49984@lists.php.net to get a copy of this message
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 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; } ---- Manual Page -- http://www.php.net/manual/en/function.fsockopen.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+32830 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+32830&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+32830&report=yes

« previous php.notes (#49984) next »