PHP Socket mock HTTP request ____php
Last Update:2018-07-24
Source: Internet
Author: User
function Http_request ($url, $type = "Get", $post _data = NULL)
{
$type = Strtoupper ($type);
$http _info = Array ();
$url 2 = 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));
$url 2["Path" = ($url 2["path"] = = ""? /": $url 2[" path "]); $url 2["Port" = ($url 2["port"] = = ""? : $url 2["Port"]);
$host _ip = http_get_host_ip ($url 2["host");
if ($result = Socket_connect ($socket, $host _ip, $url 2["Port")) < 0)
{
Socket_close ($socket);
return false;
}
$request = $url 2["path"]. ($url 2["query"]!= ""? ". $url 2[" Query ":" "). ($url 2["fragment"]!= ""? " #" . $url 2["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:". $url 2["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:". $url 2["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;
}
}