PHP Imitation ASP xmlhttprequest request data Code _php Tutorial

Source: Internet
Author: User
Tags servervariables set time urlencode
Class Name: HttpRequest ($url = "", $method = "Get", $usesocket =0)
The $url is the requested address; The default request method is GET, $usesocket defaults to 0, the Fsockopen method is used, and the Socket_create method is used if set to 1

Method:
Open ($ip = "", $port =-1)//Opens the connection with the server, the default does not set these two parameters (a colleague in Linux, the request is not hostname resolved IP, so add the two parameters to connect the real server IP)
settimeout ($timeout =0)//Set time-out to get data, must be set before the Send method call is valid, in seconds, the default value of 0 is unlimited
setRequestHeader ($key, $value = "")//Set the request header, which must be set before the Send method call is valid
Removerequestheader ($key, $value = "")//Remove the request header for the specified key value, which must be called before the Send method call is valid
Send ($data = "")//Transmit data $data to server
Getresponsebody ()//Get the text returned by the server
getAllResponseHeaders ()//Get all header information for server response
getResponseHeader ($key)//Get header information for server response, such as Server,set_cookie

Property:
$url//URL to request
$method//Request method (Post/get)
$port//Requested Port
$hostname//Host name of the request
$uri part of the//url file
$protocol//Request Protocol (HTTP) (including the 5 properties above are automatically parsed by the program via URL)
$excption//Exception information
$_headers=array ()//Request header Array ("Key" = "value")
$_senddata//data sent to the server
$status//Return status code
$statustext//status information
$httpprotocolversion//HTTP protocol version of the server

Attention:
The host header is set automatically by the program, and Content-length and Content-type are set automatically when the Post method is requested.
Pages that support gzip compression

inc.http.php Tutorial Files

Class httprequest{
Public $url, $method, $port, $hostname, $uri, $protocol, $excption, $_headers=array (), $_senddata, $status, $statustext, $ Httpprotocolversion;
Private $fp =0,$_buffer= "", $responsebody, $responseheader, $timeout =0, $usesocket;
constructor function
function __construct ($url = "", $method = "Get", $usesocket =0) {
$this->url = $url;
$this->method = Strtoupper ($method);
$this->usesocket = $usesocket;
$this->setrequestheader ("Accept", "*/*");
$this->setrequestheader ("Accept-language", "ZH-CN");
$this->setrequestheader ("accept-encoding", "gzip, deflate");
$this->setrequestheader ("User-agent", "HttpRequest Class 1.0"); Can call setRequestHeader to modify
}

Connecting to a server
Public Function open ($ip = "", $port =-1) {
if (! $this->_geturlinfo ()) return false;
$this->setrequestheader ("host", $this->hostname);
$this->setrequestheader ("Connection", "close");
$ip = ($ip = = ""? $this->hostname: $IP);
$port = ($port ==-1? $this->port: $port);
if ($this->usesocket==1) {
if (! $this->fp= $socket =socket_create (af_inet,sock_stream,0)) {
$this->excption= "Can not create socket"; return false;
}else{
if (!socket_connect ($this->fp, $ip, $port)) {
$this->excption= "Can not connect to server". $this->hostname. "On port". $this->port;return false;
}
}
}else{
if (! $this->fp=fsockopen ($ip, $port, $errno, $errstr, 10)) {
$this->excption= "Can not connect to server". $this->hostname. "On port". $this->port;return false;
}
}
return true;
}

Public function Send ($data = "") {
if (! $this->fp) {$this->excption= "is not a resource ID"; return false;}
if ($this->method== "get" && $data! = "") {
$s _str= "?";
if (Strpos ($this->uri, "?") >0) $s _str = "&";
$this->uri.= $s _str. $data;
$data = "";
}
$senddata = $this->method. " " . $this->uri. "Http/1.1rn";
if ($this->method== "post") {
$this->setrequestheader ("Content-length", strlen ($data));
$this->setrequestheader ("Content-type", "application/x-www-form-urlencoded");
}
foreach ($this->_headers as $keys = + $value) {
$senddata. = "$keys: $valuern";
}
$senddata. = "RN";
if ($this->method== "POST") $senddata. = $data;
$this->_senddata = $senddata;
if ($this->usesocket==1) {
Socket_write ($this->fp, $this->_senddata);
$buffer = "";
$timestart = time ();
do{
if ($this->timeout>0) {
if (Time ()-$timestart > $this->timeout) {break;}
}
$this->_buffer.= $buffer;
$buffer = Socket_read ($this->fp,4096);
}while ($buffer! = "");
Socket_close ($this->FP);
}else{
Fputs ($this->fp, $senddata);
$this->_buffer= "";
$timestart = time ();
while (!feof ($this->FP))
{
if ($this->timeout>0) {
if (Time ()-$timestart > $this->timeout) {break;}
}
$this->_buffer.=fgets ($this->fp,4096);
}
Fclose ($this->FP);
}
$this->_splitcontent ();
$this->_getheaderinfo ();
}

Public Function Getresponsebody () {
if ($this->getresponseheader ("content-encoding") = = "gzip" && $this->getresponseheader (" Transfer-encoding ") = =" Chunked ") {
Return Gzdecode_1 (Transfer_encoding_chunked_decode ($this->responsebody));
}else if ($this->getresponseheader ("content-encoding") = = "gzip") {
Return Gzdecode_1 ($this->responsebody);
}else{
return $this->responsebody;
}
}

Public Function getAllResponseHeaders () {
return $this->responseheader;
}

Public Function getResponseHeader ($key) {
$key = Str_replace ("-", "-", $key);
$headerstr = $this->responseheader. "RN";
$count = Preg_match_all ("/n$key: (. +?) R/is ", $headerstr, $result, Preg_set_order);
if ($count >0) {
$returnstr = "";
foreach ($result as $key 1=> $value) {
if (Strtoupper ($key) = = "Set-cookie") {
$value [1] = substr ($value [1],0,strpos ($value [1], ";"));
}
$returnstr. = LTrim ($value [1]). "; ";
}
$returnstr = substr ($returnstr, 0,strlen ($RETURNSTR)-2);
return $returnstr;
}else{return "";}
}

Public Function settimeout ($timeout =0) {
$this->timeout = $timeout;
}

Public Function setRequestHeader ($key, $value = "") {
$this->_headers[$key]= $value;
}

Public Function Removerequestheader ($key) {
if (count ($this->_headers) ==0) {return;}
$_temp=array ();
foreach ($this->_headers as $keys = + $value) {
if ($keys! = $key) {
$_temp[$keys]= $value;
}
}
$this->_headers = $_temp;
}

Split URL
Private Function _geturlinfo () {
$url = $this->url;
$count = Preg_match ("/^http://" ([^:/]+?) (:(d+))? /(.+?) $/is ", $url, $result);
if ($count >0) {
$this->uri= "/". $result [4];
}else{
$count = Preg_match ("/^http://" ([^:/]+?) (:(d+))? (/)? $/is ", $url, $result);
if ($count >0) {
$this->uri= "/";
}
}
if ($count >0) {
$this->protocol= "http";
$this->hostname= $result [1];
if (Isset ($result [2]) && $result [2]!= "") {$this->port=intval ($result [3]);} else{$this->port=80;}
return true;
}else{$this->excption= "url format error"; return false;}
}

Private Function _splitcontent () {
$this->responseheader= "";
$this->responsebody= "";
$p 1 = strpos ($this->_buffer, "rnrn");
if ($p 1>0) {
$this->responseheader = substr ($this->_buffer,0, $p 1);
if ($p 1+4 _buffer)) {
$this->responsebody = substr ($this->_buffer, $p 1+4);
}
}
}

Private Function _getheaderinfo () {
$headerstr = $this->responseheader;
$count = Preg_match ("/^http/(. +?) S (d+) s (. +?) Rn/is ", $headerstr, $result);
if ($count >0) {
$this->httpprotocolversion = $result [1];
$this->status = Intval ($result [2]);
$this->statustext = $result [3];
}
}
}


//The following two functions refer to network
Function Gzdecode_1 ($data) {
$data = ($data);
if (!function_exists (' Gzdecode ')) {
$ Flags = Ord (substr ($data, 3, 1));
$headerlen = 10;
$extralen = 0;
$filenamelen = 0;
if ($flags & 4) {
$extralen = unpack (' V ', substr ($data, 2)),
$extralen = $extralen [1];
$he Aderlen + = 2 + $extralen;
}
if ($flags & 8)//filename
$headerlen = Strpos ($data, Chr (0), $headerlen) + 1;
if ($flags & Amp +//Comment
$headerlen = strpos ($data, Chr (0), $headerlen) + 1;
if ($flags & 2)//CRC at End of FIL E
$headerlen + = 2;
$unpacked = @gzinflate (substr ($data, $headerlen));
if ($unpacked = = = False)
$UNP acked = $data;
return $unpacked;
}else{
Return Gzdecode ($data);
}
}

function Transfer_encoding_chunked_decode ($in) {
$out = "";
while ($in! = "") {
$lf _pos = Strpos ($in, "12");
if ($lf _pos = = = False) {
$out. = $in;
Break
}
$chunk _hex = Trim (substr ($in, 0, $lf _pos));
$SC _pos = Strpos ($chunk _hex, '; ');
if ($SC _pos!== false)
$chunk _hex = substr ($chunk _hex, 0, $sc _pos);
if ($chunk _hex = = "") {
$out. = substr ($in, 0, $lf _pos);
$in = substr ($in, $LF _pos + 1);
Continue
}
$chunk _len = Hexdec ($chunk _hex);
if ($chunk _len) {
$out. = substr ($in, $lf _pos + 1, $chunk _len);
$in = substr ($in, $LF _pos + 2 + $chunk _len);
} else {
$in = "";
}
}
return $out;
}
function Utf8togb ($STR) {
Return Iconv ("Utf-8", "GBK", $str);
}

function Gbtoutf8 ($STR) {
Return Iconv ("GBK", "Utf-8", $str);
}
?>

response.asp Tutorial Files

<%
Response.Cookies ("a") = "Anlige"
Response.Cookies ("a"). Expires = DATEADD ("yyyy", 1,now ())
Response.Cookies ("B") ("C") = "WSDASDADSA"
Response.Cookies ("B") ("D") = "ddd"
Response.Cookies ("B"). Expires = DATEADD ("yyyy", 1,now ())
Response.Write "QueryString:" & Request.QueryString & "
"
For each V in Request.QueryString
Response.Write V & "=" & Request.QueryString (v) & "
"
Next
Response.Write "
Form: "& Request.Form &"
"
For each V in Request.Form
Response.Write V & "=" & Request.Form (v) & "
"
Next
Response.Write "
URL: "& Request.ServerVariables (" url ") &"
"
Response.Write "Referer:" & Request.ServerVariables ("Http_referer") & "
"
Response.Write "Host:" & Request.ServerVariables ("Http_host") & "
"
Response.Write "User-agent:" & Request.ServerVariables ("Http_user_agent") & "
"
Response.Write "Cookies" & Request.ServerVariables ("Http_cookie")
%>

index.php file

Get Pass Data
Post transfer data
Send an unsolicited message to the server
Send user-agent to Server
Get the status returned by the server
Get Server response Header
Save picture



Include ("inc_http.php");
$responseurl = "http://dev.mo.cn/aiencode/http/response.asp";

$act = Isset ($_get["action"])? $_get["Action"]: "";
if ($act = = "Get") {//get data

$myhttp = new HttpRequest ("$responseurl a=text");
$myhttp->open ();
$myhttp->send ("name=anlige&city=". UrlEncode ("Hangzhou"));
Echo ($myhttp->getresponsebody ());

}else if ($act = = "Post") {//post data transfer

$myhttp = new HttpRequest ("$responseurl a=text", "post");
$myhttp->open ();
$myhttp->send ("name=anlige&city=". UrlEncode ("Hangzhou"));
Echo ($myhttp->getresponsebody ());

}else if ($act = = "Header_referer") {//Send routing information to the server

$myhttp = new HttpRequest ("$responseurl a=text", "post");
$myhttp->open ();
$myhttp->setrequestheader ("Referer", "http://www.baidu.com");
$myhttp->send ("name=anlige&city=". UrlEncode ("Hangzhou"));
Echo ($myhttp->getresponsebody ());

}else if ($act = = "Header_useragent") {//Send user-agent to Server

$myhttp = new HttpRequest ("$responseurl a=text", "post");
$myhttp->open ();
$myhttp->setrequestheader ("Referer", "http://www.baidu.com");
$myhttp->setrequestheader ("User-agent", "mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; trident/4.0)");
$myhttp->send ("name=anlige&city=". UrlEncode ("Hangzhou"));
Echo ($myhttp->getresponsebody ());

}else if ($act = = "status") {//Gets the state returned by the server

$myhttp = new HttpRequest ("$responseurl a=text", "post");
$myhttp->open ();
$myhttp->send ("name=anlige&city=". UrlEncode ("Hangzhou"));
Echo ($myhttp->status. " " . $myhttp->statustext. "

");
Echo ($myhttp->getresponsebody ());

}else if ($act = = "Get_headers") {//Get server response header

$myhttp = new HttpRequest ("$responseurl a=text", "get");
$myhttp->open ();
$myhttp->send ("name=anlige&city=". UrlEncode ("Hangzhou"));
Echo ($myhttp->getallresponseheaders (). "

");
Echo ($myhttp->getresponseheader ("Server").

");

}else if ($act = = "Get_image") {

$myhttp = new HttpRequest ("Http://www.baidu.com/img/baidu_logo.gif");
$myhttp->open ();
$myhttp->send ();
$fp = @fopen ("Demo.gif", "w");
Fwrite ($fp, $myhttp->getresponsebody ());
Fclose ($FP);
Echo ("");
}

?>


http://www.bkjia.com/PHPjc/444789.html www.bkjia.com true http://www.bkjia.com/PHPjc/444789.html techarticle class Name: HttpRequest ($url =, $method =get, $usesocket =0)//$url is the requested address; The default request method is get; $usesocket default is 0, using the Fsockopen method, If set to 1 then use so ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.