php通过socket发送http请求

function httpRequest($url, $type = "GET", $post_data = NULL){
	$http_info = array();
	$url2 = parse_url($url);
	if(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
		return false;
	}
	//set socket timeout
	socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO,	array("sec"=>20, "usec"=>0));
	$url2["path"] = isset($url2["path"]) && !empty($url2["path"]) ?  $url2["path"] :  "/";
	$url2["port"] = isset($url2["port"]) && !empty($url2["port"]) ? $url2["port"] : 80;
	$host_ip = gethostbyname($url2["host"]);
	if(($result = socket_connect($socket, $host_ip, $url2["port"])) < 0) {
		socket_close($socket);
		return false;
	}

	$url2["query"] = isset($url2["query"]) && !empty($url2["query"]) ? '?'.$url2["query"] : '';
	$url2["fragment"] = isset($url2["fragment"]) && !empty($url2["fragment"]) ? '#'.$url2["query"] : '';
	$request =  $url2["path"] . $url2["query"] . $url2["fragment"];
	if($type == "GET") {
		//GET method
		$in = "GET " . $request . " HTTP/1.1\r\n";
		$in .= "Accept: */*\r\n";
		$in .= "User-Agent: Lowell-Agent\r\n";
		$in .= "Host: " . $url2["host"] . "\r\n";
		$in .= "Connection: Close\r\n\r\n";
		if(!socket_write($socket, $in, strlen($in))) {
			socket_close($socket);
			return false;
		}
		unset($in);
	} else if($type == "POST") {
		//POST method
		//build post data
		$needChar = false;
		$post_data2 = '';
		foreach($post_data as $key => $val) {
			$post_data2 .= ($needChar ? "&" : "") . urlencode($key) . "=" . urlencode($val);
			$needChar = true;
		}
		$in = "POST " . $request . " HTTP/1.1\r\n";
		$in .= "Accept: */*\r\n";
		$in .= "Host: " . $url2["host"] . "\r\n";
		$in .= "User-Agent: Lowell-Agent\r\n";
		$in .= "Content-type: application/x-www-form-urlencoded\r\n";
		$in .= "Content-Length: " . strlen($post_data2) . "\r\n";
		$in .= "Connection: Close\r\n\r\n";
		$in .= $post_data2 . "\r\n\r\n";
		unset($post_data2);
		if(!@socket_write($socket, $in, strlen($in))) {
			socket_close($socket);
			return false;
		}
		unset($in);
	} else {
		//unknowd method
		trigger_error("Unknowd method", E_USER_ERROR);
		exit;
	}
	//process response
	$out = "";
	while($buff = @socket_read($socket, 2048)) {
		$out .= $buff;
	}
	//finish socket
	socket_close($socket);
	$pos = strpos($out, "\r\n\r\n");
	$head = substr($out, 0, $pos);		//http head
	$status = substr($head, 0, strpos($head, "\r\n"));		//http status line
	$body = substr($out, $pos + 4, strlen($out) - ($pos + 4));		//page body
	if(preg_match("/^HTTP\/\d\.\d\s([\d]+)\s.*$/", $status, $matches)) {
		if(intval($matches[1]) / 100 == 2) {
			return $body;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

你可能感兴趣的:(PHP,socket,服务器发送http请求)