PHP uses sockets to send get,post requests

Source: Internet
Author: User
Tags fread

As a PHP programmer must be exposed to the HTTP protocol, and only in-depth understanding of the HTTP protocol, programming level will be further. Recently I have been learning PHP for HTTP programming, a lot of things suddenly, benefited. I want to share it with you. This article requires developers with certain HTTP basics to read.

Today brings you how to use the socket to send a get,post request. I borrowed the Swallow 18 teacher encapsulated an HTTP class to be described.

In everyday programming I believe a lot of people are the same as me most of the time is to use the browser to make Get,post requests to the server, then can you use other methods to make Get,post requests? The answer must be yes. People who have known about the HTTP protocol know that the essence of a browser submission request is to send a request message to the server, which has a request line, a request header, and a request body (not required). The server returns a response message based on the requested information. The connection is broken.

The format of the HTTP request is as follows:

1 < Request-line > 2 < Headers > 3 <  line>4 [<request-body>]

The format of the HTTP response is very similar to the format of the request:

< Status-line > < Headers > <  line>[<response-body>]

We can use HTTP to send a request to the principle that you can reconsider the use of the socket to send HTTP requests.

The English literal of the socket is "hole" or "socket". Often also referred to as a "socket," which describes 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 binds to a port, and the different ports correspond to different services. In this case, it is just as easy to use the socket for remote files and read and write local files as the local files are transmitted through the hardware and the remote files are transmitted over the network cable.

Thus the sending request can be taken into account to establish connection, open socket Interface (Fsockopen ()), write Request (Fwrite ()), read-Out response (Fread (), Close file (fclose ()). Words not much to say, directly on the code:

  

<?PHPInterfaceProto {//Connection URL    functionConn$url); //send a Get query    functionget (); //Send post Query    functionpost (); //Close Connection    functionclose ();}classHttpImplementsProto {ConstCRLF = "\ 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 writing the request line    protected functionSetline ($method) {        $this->line[0] =$method. ‘ ‘ .$this->url[' path '. ‘?‘ .$this->url[' query ']. ‘ ‘.$this-version; }    //This method is responsible for writing header information     Public functionSetHeader ($headerline) {        $this-Header[] =$headerline; }    //This method is responsible for writing the principal information    protected functionSetbody ($body) {         $this->body[] =Http_build_query($body); }    //Connection URL     Public functionConn$url) {        $this->url =Parse_url($url); //Determine the port        if(!isset($this->url[' Port '])) {            $this->url[' port '] = 80; }        //Judging Query        if(!isset($this->url[' query '])) {            $this->url[' query '] = '; }        $this-&GT;FH =Fsockopen($this->url[' Host '],$this->url[' Port '],$this->errno,$this->errstr,3); }    //constructing data for GET requests     Public functionget () {$this->setline (' GET '); $this-request (); return $this-response; }    //constructing data for a post query     Public functionPost$body=Array()) {              $this->setline (' POST '); //Design Content-type        $this->setheader (' content-type:application/x-www-form-urlencoded '); //design body information, which is different than get        $this->setbody ($body); //Calculate Content-length        $this->setheader (' Content-length: '.strlen($this->body[0])); $this-request (); return $this-response; }    //really request     Public functionrequest () {//Put the request line, header information, entity information in an array, easy to splice        $req=Array_merge($this->line,$this-Header,Array(‘‘),$this->body,Array(‘‘)); //Print_r ($req);        $req=implode(Self::crlf,$req); //echo $req; exit;        fwrite($this-&GT;FH,$req);  while(!feof($this-FH)) {            $this->response. =fread($this->fh,1024); }        $this->close ();//Close Connection    }    //Close Connection     Public functionClose () {fclose($this-FH); }}

Use this class to send a simple GET request:

<? PHP

Remember to refer to the HTTP class $url= "http://home.cnblogs.com/u/DeanChopper/"; $http=new http ($url); $response=$http, get (); Print_r ($response);

The return value is information that allows you to further process the response information to get what you want.

  

  

PHP uses sockets to send get,post requests

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.