我是靠谱客的博主 无心小天鹅,最近开发中收集的这篇文章主要介绍PHP SOCKET模拟HTTP请求,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述


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.1rn";
$in .= "Accept: */*rn";
$in .= "User-Agent: Lowell-Agentrn";
$in .= "Host: " . $url2["host"] . "rn";
$in .= "Connection: Closernrn";
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.1rn";
$in .= "Accept: */*rn";
$in .= "Host: " . $url2["host"] . "rn";
$in .= "User-Agent: Lowell-Agentrn";
$in .= "Content-type: application/x-www-form-urlencodedrn";
$in .= "Content-Length: " . strlen($post_data2) . "rn";
$in .= "Connection: Closernrn";
$in .= $post_data2 . "rnrn";
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, "rnrn");
$head = substr($out, 0, $pos); //http head
$status = substr($head, 0, strpos($head, "rn")); //http status line
$body = substr($out, $pos + 4, strlen($out) - ($pos + 4)); //page body
if(preg_match("/^HTTP/d.ds([d]+)s.*$/", $status, $matches))
{
if(intval($matches[1]) / 100 == 2)
{
return $body;
}else{
return false;
}
}else{
return false;
}
}

最后

以上就是无心小天鹅为你收集整理的PHP SOCKET模拟HTTP请求的全部内容,希望文章能够帮你解决PHP SOCKET模拟HTTP请求所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部