Php-like aspxmlhttprequest request data code _ PHP Tutorial

Source: Internet
Author: User
Php imitates the data code of the aspxmlhttprequest request. Class name: httprequest ($ url, $ methodget, $ usesocket0) $ url indicates the request address. the default request method is get; $ usesocket is 0 by default, and fsockopen is used, if set to 1, use the so class name: httprequest ($ url = "", $ method = "get", $ usesocket = 0)
// $ Url indicates the request address. the default request method is get. $ usesocket defaults to 0 and fsockopen is used. if it is set to 1, socket_create is used.

Method:
Open ($ ip = "", $ port =-1) // open the connection to the same server. by default, you do not need to set these two parameters (when a colleague is using linux, the requested ip address is not resolved by the hostname. Therefore, these two parameters are added to connect to the real server ip address)
Settimeout ($ timeout = 0) // sets the time-out time for data retrieval. The value is valid only before the send method is called. the default value is 0, which is unlimited.
Setrequestheader ($ key, $ value = "") // sets the request header, which must be set before the send method is called.
Removerequestheader ($ key, $ value = "") // removes the request header with the specified key value, which must be called before the send method is called.
Send ($ data = "") // send $ data to the server
Getresponsebody () // get the text returned by the server
Getallresponseheaders () // get all the header information of the server response
Getresponseheader ($ key) // Obtain a header of the server response, such as server and set_cookie.

Attribute:
$ Url // the url to be requested
$ Method // request method (post/get)
$ Port // request port
$ Hostname // the requested host name
$ Uri // The File part of the url
$ Protocol // request protocol (http) (more than five attributes including this attribute are automatically analyzed by the program through url)
$ Excption // exception information
$ _ Headers = array () // request header array ("key" => "value ")
$ _ Senddata // data sent to the server
$ Status // returned status code
$ Statustext // status information
$ Httpprotocolversion // http protocol version of the server

Note:
The host header is automatically set by the program. when a post request is used, content-length and content-type are automatically set.
Pages that support gzip compression

Inc. http. php Tutorial file

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 _ 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"); // you can use setrequestheader to modify
}

// Connect to the 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 $ key1 => $ 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 the 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 = "";
$ P1 = strpos ($ this-> _ buffer, "rnrn ");
If ($ p1> 0 ){
$ This-> responseheader = substr ($ this-> _ buffer, 0, $ p1 );
If ($ p1 + 4 _ Buffer )){
$ This-> responsebody = substr ($ this-> _ buffer, $ p1 + 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];
}
}
}


// Refer to the network for the following two functions:
Function gzdecode_1 ($ data ){
$ Data = ($ data );
If (! Function_exists ('gzdemo ')){
$ Flags = ord (substr ($ data, 3, 1 ));
$ Headerlen = 10;
$ Extralen = 0;
$ Filenamelen = 0;
If ($ flags & 4 ){
$ Extralen = unpack ('v', substr ($ data, 10, 2 ));
$ Extralen = $ extralen [1];
$ Headerlen + = 2 + $ extralen;
}
If ($ flags & 8) // filename
$ Headerlen = strpos ($ data, chr (0), $ headerlen) + 1;
If ($ flags & 16) // comment
$ Headerlen = strpos ($ data, chr (0), $ headerlen) + 1;
If ($ flags & 2) // crc at end of file
$ Headerlen + = 2;
$ Unpacked = @ gzinflate (substr ($ data, $ headerlen ));
If ($ unpacked = false)
$ Unpacked = $ 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 file

<%
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 "cookie" & request. servervariables ("http_cookie ")
%>

Index. php file

Get Data transmission
Post data transmission
Send incoming route information to the server
Send user-agent to the server
Obtain the status returned by the server
Get server response header
Save Image



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

$ Act = isset ($ _ get ["action"])? $ _ Get ["action"]: "";
If ($ act = "get") {// get Data transmission

$ Myhttp = new httprequest ("$ responseurl? A = text ");
$ Myhttp-> open ();
$ Myhttp-> send ("name = anlige & city =". urlencode ("Hangzhou "));
Echo ($ myhttp-> getresponsebody ());

} Else if ($ act = "post") {// post data transmission

$ 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 the route 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 the user-agent to the 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") {// get the status 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 the 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 ("");
}

?>


Authorization: httprequest ($ url =, $ method = get, $ usesocket = 0) // $ url indicates the request address. the default request method is get. $ usesocket defaults to 0, use the fsockopen method. if it is set to 1, 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.