PHP SOCKET模拟HTTP请求

来源:互联网 发布:孕妇照软件下载 编辑:程序博客网 时间:2024/05/21 12:04

function http_request($url, $type = "GET", $post_data = NULL)
{
$type = strtoupper($type);

$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"=>1, "usec"=>0));
$url2["path"] = ($url2["path"] == "" ? "/" : $url2["path"]);$url2["port"] = ($url2["port"] == "" ? 80 : $url2["port"]);
$host_ip = http_get_host_ip($url2["host"]);
if(($result = socket_connect($socket, $host_ip, $url2["port"])) < 0)
{
socket_close($socket);
return false;
}


$request =  $url2["path"] . ($url2["query"] != "" ? "?" . $url2["query"] : "") . ($url2["fragment"] != "" ? "#" . $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;
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;
}
}
0 0
原创粉丝点击