PHP SOCKET類比HTTP請求____PHP

來源:互聯網
上載者:User

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;
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.