关闭

PHP SOCKET模拟HTTP请求

315人阅读 评论(0) 收藏 举报
分类:

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

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:94741次
    • 积分:1633
    • 等级:
    • 排名:千里之外
    • 原创:63篇
    • 转载:40篇
    • 译文:0篇
    • 评论:8条
    文章分类
    最新评论