Use PHPSocket programming to simulate Httppost and get requests

Source: Internet
Author: User
This article describes how to simulate Httppost and get requests using PHPSocket programming. if you need to simulate Http post AND get requests using PHP Socket programming, refer to the following code to share with you, very practical. In the end, we will discuss several methods for php to simulate http requests.

The code is as follows:


<? Php /**
* Simulate Http post AND get requests using PHP Socket programming
* @ Author koma
*/Class Http {
Private $ sp = "\ r \ n"; // The double quotation mark private $ protocol = 'http/123' must be written here ';
Private $ requestLine = "";
Private $ requestHeader = "";
Private $ requestBody = "";
Private $ requestInfo = "";
Private $ fp = null;
Private $ urlinfo = null;
Private $ header = array ();
Private $ body = "";
Private $ responseInfo = "";
Private static $ http = null; // Http object Singleton
Private function _ construct (){}
Public static function create (){
If (self ::$ http === null ){
Self: $ http = new Http ();
}
Return self: $ http;
}
Public function init ($ url ){
$ This-> parseurl ($ url );
$ This-> header ['host'] = $ this-> urlinfo ['host'];
Return $ this;
}
Public function get ($ header = array ()){
$ This-> header = array_merge ($ this-> header, $ header );
Return $ this-> request ('get ');
}
Public function post ($ header = array (), $ body = array ()){
$ This-> header = array_merge ($ this-> header, $ header );
If (! Empty ($ body )){
$ This-> body = http_build_query ($ body );
$ This-> header ['content-type'] = 'application/x-www-form-urlencoded ';
$ This-> header ['content-length'] = strlen ($ this-> body );
}
Return $ this-> request ('post ');
}
Private function request ($ method ){
$ Header = "";
$ This-> requestLine = $ method. ''. $ this-> urlinfo ['path']. '? '. $ This-> urlinfo ['query'].'. $ this-> protocol;
Foreach ($ this-> header as $ key => $ value ){
$ Header. = $ header = ""? $ Key. ':'. $ value: $ this-> sp. $ key. ':'. $ value;
}
$ This-> requestHeader = $ header. $ this-> sp. $ this-> sp;
$ This-> requestInfo = $ this-> requestLine. $ this-> sp. $ this-> requestHeader;
If ($ this-> body! = ""){
$ This-> requestInfo. = $ this-> body;
}
/*
* Note: the url parameter format in fsockopen is "www.xxx.com"
* It cannot contain "http: //"
*/
$ Port = isset ($ this-> urlinfo ['port'])? Isset ($ this-> urlinfo ['port']): '80 ';
$ This-> fp = fsockopen ($ this-> urlinfo ['host'], $ port, $ errno, $ errstr );
If (! $ This-> fp ){
Echo $ errstr. '('. $ errno .')';
Return false;
}
If (fwrite ($ this-> fp, $ this-> requestInfo )){
$ Str = "";
While (! Feof ($ this-> fp )){
$ Str. = fread ($ this-> fp, 1024 );
}
$ This-> responseInfo = $ str;
}
Fclose ($ this-> fp );
Return $ this-> responseInfo;
}
Private function parseurl ($ url ){
$ This-> urlinfo = parse_url ($ url );
}
} // $ Url = "http://news.163.com/14/1102/01/AA0PFA7Q00014AED.html ";
$ Url = "http: // localhost/httppro/post. php"; $ http = Http: create ()-> init ($ url);/* send a get request
Echo $ http-> get (array (
'User-agent' => 'mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/8080 ',
));
*/
/* Send a post request */echo $ http-> post (array (
'User-agent' => 'mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/8080 ',
), Array ('username' => 'Send a Chinese', 'age' => 22 ));

Php simulates http requests

Method 1: use php socket programming to directly send data to the interface to simulate post operations.

Create two files: post. php and getpost. php.
The post. php content is as follows:

The code is as follows:


<? Php
$ Flag = 0;
$ Params = '';
$ Errno = '';
$ Errstr = '';
// Data to be post
$ Argv = array (
'Var1' => 'ABC ',
'Var2' => 'How are you, my friend ?? ');
// Construct the string to post
Foreach ($ argv as $ key => $ value ){
If ($ flag! = 0 ){
$ Params. = "&";
$ Flag = 1;
}
$ Params. = $ key. "="; $ params. = urlencode ($ value );
$ Flag = 1;
}
$ Length = strlen ($ params );
// Create a socket connection
$ Fp = fsockopen ("localhost", 81, $ errno, $ errstr, 10) or exit ($ errstr. "--->". $ errno );
// Construct the post request header
$ Header = "POST/flandy/getpost. php HTTP/1.1 \ r \ n ";
$ Header. = "Host: 127.0.0.1 \ r \ n ";
$ Header. = "Referer:/flandy/post. php \ r \ n ";
$ Header. = "Content-Type: application/x-www-form-urlencoded \ r \ n ";
$ Header. = "Content-Length:". $ length. "\ r \ n ";
$ Header. = "Connection: Close \ r \ n ";
// Add the post string
$ Header. = $ params. "\ r \ n ";

// Send post data
Fputs ($ fp, $ header );
$ Inheader = 1;
While (! Feof ($ fp )){
$ Line = fgets ($ fp, 1024); // only the returned data on the page is displayed when the request packet header is removed.
If ($ inheader & ($ line = "\ n" | $ line = "\ r \ n ")){
$ Inheader = 0;
}
If ($ inheader = 0 ){
Echo $ line;
}
}

Fclose ($ fp );
?>

The content of getpost. php is as follows:

The code is as follows:


<? Php
Echo "this is the data posted ";
Echo"

";
print_r($_REQUEST);
echo "
";
?>

Result output:

The code is as follows:


This is the data postedArray
(
[Var1] => abc
[Var2] => how are you, my friend ??
)

The above code has passed the test on port 81 of the local machine.

Method 2:

Use the curl extension of PHP or the HttpClient. class. php class. These two are very similar. the implementation code of curl is briefly listed below.
Two files: post2.php and getpost2.php
Post2.php content is as follows:

The code is as follows:


<? Php
$ Response code = 'nde005 ';
$ Website = 'www .baidu.com ';
$ Amt = 1;
$ Pwd = 123456;
$ Ch = curl_init ();
$ Curl_url = "http: // localhost: 81/flandy/getpost2.php? Web = ". $ website.
"& Pwd =". $ pwd. "& action = check & consumer id =". $ response code.
"& Amt =". $ amt;
Curl_setopt ($ ch, CURLOPT_URL, $ curl_url );
Curl_setopt ($ ch, CURLOPT_POST, 1 );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); // no direct output is returned to the variable
$ Curl_result = curl_exec ($ ch );
$ Result = explode (',', $ curl_result );
Curl_close ($ ch );
Print_r ($ result );
?>

The getpost2.php content is as follows:

The code is as follows:


<? Php
Echo "returndata
";
Echo"

";
print_r($_REQUEST);
echo "
";
?>

Result output:

The code is as follows:


Array ([0] => returndataArray
(
[Web] => 'wwwbaiducom'
[Pwd] = & gt; 123456
[Action] => check
[Shard ID] => 'nde005'
[Amt] => 1
)
)

Method 3:

The third-party class library HttpClient can be downloaded here: http://scripts.incutio.com/httpclient/

The code is as follows:


<? Php
Require_once 'httpclient. class. php ';
$ Params = array ('web' => 'Www .baidu.com ',
'Pwd' => '123 ',
'Action' => 'check ',
'Upload ID' => 'nde005 ',
'Amt '=> 1 );
$ PageContents = HttpClient: quickPost ('http: // localhost: 81/flandy/getpost3.php', $ params );
$ Result = explode (',', $ pageContents );
Print_r ($ result );
?>

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.