HTTPRequest_GET() - Perform an HTTP GET request and return the body and headers.


PHP Code
function HTTPRequest_GET($url, $Timeout = null) {
	/*
	Purpose
		Used to make an HTTP GET request.
	Parameters
		URL (String) = The URL we want to make a request to.
		Timeout (Optional Integer) = The timeout value used when opening the connection to the server.
			Unit of measure is seconds.
			Default: 15
	Return (Associative Array)
		Members:
			"headers"	(Associative Array) This contains an array of all returned headers.
						The key of each element contains the name of each header.
						The value of each element contains the value of each header.
			"body"		(String) This contains the entire body of the requested page.
						This returns zero-length if:
							- An error occurs ("status" is not zero).
			"status"	(Integer) Returns a code indicating the status of the request.
						Valid values:
							0	No errors occurred
							1	Error making connection.
								"errcode" and "errmsg" contain values returned from fsockopen().
			"errnum"	(Integer) The error number returned by an internal PHP call.
			"errmsg"	(String) The error message returned by an internam PHP call.
	Version History
		1.0 2010.10.05 Tested by Russ Tanner on PHP 5.1.6.
			This function may not work when passed URLs that redirect more than 1 time.
		1.1 2014.03.14 Tested by Russ Tanner on PHP 5.3.8.
			Predefined "$response" to eliminate PHP Notice.
			Muted error using "@" on fsockopen() to eliminate PHP Notice.
	*/
	
	$r = array(
		'status' => 0,
		'errnum' => 0,
		'errmsg' => '',
		'headers' => array(),
		'body' => ''
	);

	// Default parameters.
	if (is_null($Timeout)) $Timeout = 15;

	$ErrNum = 0;		// Used to capture error information from PHP functions.
	$ErrMsg = '';


	// Parse the specified URL into its component parts...
	$Request = $url;

	// Parse the protocol.
	$i = strpos($Request, '://');
	$Protocol = strtolower(substr($Request, 0, $i));

	// Parse the host.
	$Request = substr($Request, $i + 3);
	$i = strpos($Request, '/');
	// No path delimiter found. The entire remaining request string must be the host.
	if($i === false) $i = strlen($Request);
	$host_ = substr($Request, 0, $i);

	// Parse the port. The host contains a colon. Parse the host and port number.
	if(strpos($host_, ':') !== false) list($Host, $Port) = explode(':', $host_);
	// The host does not contains a colon. We only have the host.
	else {
		$Host = $host_;
		$Port = ($Protocol == 'https') ? 443 : 80;		// Determine the port by the specified protocol.
	}

	// Parse the URI.
	$uri = substr($Request, $i);
	// No URI found. Default it to "root".
	if($uri == '') $uri = '/';


	// Format the request string.
	$Request =
		"GET $uri HTTP/1.0\r\n" .
		"Host: $Host\r\n" .
		"\r\n";


	// Open the connection.
	$fp = @fsockopen(($Protocol == 'https' ? 'ssl://' : '') . $Host, $Port, $ErrNum, $ErrMsg,  $Timeout);
	// Error Trap: Error opening the connection. Report the error and return.
	if ($ErrNum != 0) {
		$r['status'] = 1;
		$r['errnum'] = $ErrNum;
		$r['errmsg'] = $ErrMsg;
		return $r;
	}
	
	// Send the request, read the response, and close the connection.
	fwrite($fp, $Request);
	$response = '';
	while(is_resource($fp) && $fp && !feof($fp)) $response .= fread($fp, 4096);
	fclose($fp);

	// Parse the header and body.
	$i = strpos($response, "\r\n\r\n");
	// No headers returned, only body. Return the body now.
	if($i === false) {
		$r['body'] = $response;
		return $r;
	}
	// Header found. Separate the header and the body.
	$header = substr($response, 0, $i);
	$r['body'] = substr($response, $i + 4);
   
	// Parse the individual headers and normalize header keys (trim and turn to lower-case).
	$lines = explode("\r\n", $header);
	foreach($lines as $line)
		if(($pos = strpos($line, ':')) !== false)
			$r['headers'][strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos + 1));

	// This request sent a redirection. Redirect now.
	if(isset($r['headers']['location'])) return HTTPRequest_GET($r['headers']['location'], $Timeout);

	// Return all fields.
	return $r;

} 

Last edited by Russ; 03/14/14 09:07 PM.

The Captian
Today they call you "crazy". Tomorrow they call you "ahead of your time."
Global Skywatch Learn about Chemtrails - You're breathing them now!
OnlyTheBestHerbs.com World-class supplements
Mercury Talk Why you are sick.
OneUp Domains Domains, Hosting, Email
1-800-358-4278 (U.S. & Canada)