Simulate HTTP post and GET request _php instances using PHP Socket programming

Source: Internet
Author: User
Tags curl explode http post http request

Here to share a section using PHP Socket programming to simulate the HTTP post and get request code, very practical, the end of the section we discuss the PHP simulation of HTTP request several methods.

Copy Code code as follows:

<?php/**
* Use PHP Socket programming to simulate HTTP POST and get requests
* @author Koma
* * Class http{
Private $SP = "\ r \ n"; Here must be written in double quotes private $protocol = ' http/1.1 ';
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 Single Example
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 in the fsockopen here is "www.xxx.com"
* Can not bring "http://" this
*/
$port = isset ($this->urlinfo[' Port ')? Isset ($this->urlinfo[' Port ']): ' 80 ';
$this-&GT;FP = fsockopen ($this->urlinfo[' host '), $port, $errno, $ERRSTR);
if (! $this-&GT;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-&GT;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 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/537.36 ',
));
*/
* * Send 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/537.36 ',
), Array (' username ' => ' sends a Chinese ', ' age ' =>22));

PHP Mock HTTP request

Method one: Using PHP's socket programming to directly send data to the interface to simulate the post operation.

Create two files post.php,getpost.php
post.php contents are as follows:

Copy Code code as follows:

<?php
$flag = 0;
$params = ';
$errno = ';
$errstr = ';
The data to post
$ARGV = Array (
' var1 ' => ' abc ',
' Var2 ' => ' How to 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", Bayi, $errno, $errstr,) or exit ($ERRSTR.) ---> ". $errno);
To construct the header of a POST request
$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\r\n";
Add a Post string
$header. = $params. " \ r \ n ";

Send the Post data
Fputs ($fp, $header);
$inheader = 1;
while (!feof ($fp)) {
$line = fgets ($fp, 1024); Removing the header of the request package shows only the return data of the page
if ($inheader && ($line = = "\ n" | | $line = = "\ r \ n")) {
$inheader = 0;
}
if ($inheader = = 0) {
Echo $line;
}
}

Fclose ($FP);
?>

The contents of getpost.php are as follows

Copy Code code as follows:

<?php
echo "This is the data posted";
echo "<pre>";
Print_r ($_request);
echo "</pre>";
?>

Result output:

Copy Code code as follows:

This is the data postedarray
(
[VAR1] => ABC
[VAR2] => How are your, my friend??
)

The above code has passed the test under native port 81.

Method Two:

Using PHP's Curl extensions or HttpClient.class.php classes, these two are very similar, and the following is a simple listing of the Curl implementation code.
Two files post2.php and getpost2.php
The contents of post2.php are as follows:

Copy Code code as follows:

<?php
$psecode = ' 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&pseid=". $psecode.
"&amt=". $amt;
curl_setopt ($ch, Curlopt_url, $curl _url);
curl_setopt ($ch, Curlopt_post, 1);
curl_setopt ($ch, Curlopt_returntransfer, 1)//not directly output, return to variable
$curl _result = curl_exec ($ch);
$result = Explode (', ', $curl _result);
Curl_close ($ch);
Print_r ($result);
?>

The contents of getpost2.php are as follows:

Copy Code code as follows:

<?php
echo "Returndata<br>";
echo "<pre>";
Print_r ($_request);
echo "</pre>";
?>

Result output:

Copy Code code as follows:

Array ([0] => Returndataarray
(
[web] => ' wwwbaiducom '
[PWD] => 123456
[Action] => check
[Pseid] => ' NDE005 '
[Amt] => 1
)
)

Method Three:

This will take advantage of the third party class library httpclient can download here: http://scripts.incutio.com/httpclient/

Copy Code code as follows:

Require_once ' HttpClient.class.php ';
$params = Array (' web ' => ' www.baidu.com '),
' pwd ' => ' 123456 ',
' Action ' => ' check ',
' Pseid ' => ' 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.