Today brings to you how to use the socket to send Get,post request. I borrowed an HTTP class encapsulated by Yan 18 teacher to explain.
In everyday programming, I believe many people like me spend most of their time using browsers to make Get,post requests to the server, so can you make get,post requests in other ways? The answer must be yes. Anyone who understands the HTTP protocol knows that the essence of the browser submission request is to send a request message to the server, which has the request line, the request header, and the request body (not required) to make up. The server returns a response information based on the request information. The connection is disconnected.
The format of the HTTP request is as follows:
The format of the HTTP response is very similar to the format of the request:
We can use the HTTP send request principle, may reconsider uses the socket to send the HTTP request.
The original meaning of the socket is "hole" or "socket". Commonly referred to as "sockets", used to describe IP addresses and ports, is a handle to a communication chain that can be used to communicate between different virtual machines or different computers. Hosts on the internet typically run multiple service software, while providing several services. Each service opens a socket and is bound to a port where different ports correspond to different services. So it seems that, in fact, the use of sockets to operate remote files and read and write local files as easy, the local file as a hardware transmission, remote file transmission through the network line.
The send request can therefore be considered as establishing a connection-> open the Socket Interface (Fsockopen ())-> write Request (fwrite ())-> read out response (Fread ()-> Close the file (Fclose ()). Words not much to say, directly on the code:
<?php interface Proto {//connection URL function conn ($url);
Send a Get Query function get ();
Send post query function post ();
Closes the connection function close ();
Class Http implements Proto {Const CRLF = "\ r \ n";
protected $errno =-1;
protected $errstr = ';
protected $response = ';
protected $url = null;
protected $version = ' http/1.1 ';
protected $fh = null;
protected $line = Array ();
Protected $header = Array ();
Protected $body = Array ();
Public function __construct ($url) {$this->conn ($url);
$this->setheader (' Host: '. $this->url[' host ')); }//This method is responsible for write request line protected function Setline ($method) {$this->line[0] = $method. ' ' . $this->url[' path ']. '->url['. $this ' query ']. ' '.
$this->version;
//This method is responsible for the write header information public function SetHeader ($headerline) {$this->header[] = $headerline;
}//This method is responsible for writing the body information protected function Setbody ($body) {$this->body[] = http_build_query ($body); }//Connection URL public functIon Conn ($url) {$this->url = Parse_url ($url);
To determine the port if (!isset ($this->url[' Port ')) {$this->url[' port ' = 80;
//Judge Query if (!isset ($this->url[' query ')) {$this->url[' query '] = ';
$this->fh = fsockopen ($this->url[' host '), $this->url[' Port ', $this->errno, $this->errstr,3);
}//construct the data public function of Get request () {$this->setline (' get ');
$this->request ();
return $this->response;
The data public function post ($body = Array ()) {$this->setline (' post ') of the post query is constructed.
Design Content-type $this->setheader (' content-type:application/x-www-form-urlencoded ');
Design subject information, than get different places $this->setbody ($body);
Compute content-length $this->setheader (' content-length: ' strlen ($this->body[0));
$this->request ();
return $this->response; //Real Request Public Function request () {//Put the request line, header information, entity information in an array for easy stitching $req = Array_merge ($this->liNE, $this->header,array ("), $this->body,array ("));
Print_r ($req);
$req = Implode (Self::crlf, $req); Echo $req;
Exit
Fwrite ($this->fh, $req);
while (!feof ($this->fh)) {$this->response. = fread ($this->fh,1024); } $this->close ();
Close Connection}//Turn off connection public function close () {fclose ($this->fh);
}
}
Use this class to send a simple GET request:
<?php
//Remember to refer to
the HTTP class $url = "http://home.jb51.net/u/DeanChopper/";
$http =new http ($url);
$response = $http->get ();
Print_r ($response);
The return value is information that can be further processed for the response information to get what you want.
Let's take a look at the next concrete example
<?php/** * uses 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 p
Rivate $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 Instance 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;
The Public function get ($header = Array ()) {$this->header = Array_merge ($this->header, $header);
return $this->request (' get '); The 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 take "http://" this * * * $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 GET request echo $http->get (' 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 (' 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));