Php uses socket to send HTTP requests (GET, POST), socketget
What we bring to you today is how to use socket to send GET and POST requests. I used an Http class encapsulated by instructor Yan 18 to explain it.
In daily programming, I believe that many people, like me, spend most of their time using browsers to send GET and POST requests to the server. Can they use other methods to submit GET and POST requests? The answer must be yes. People who know the HTTP protocol know that the essence of a browser request is to send a request information to the server, which consists of the request line, request header, and request body (not required. The server returns a response message based on the request information. The connection is disconnected.
The HTTP request format is as follows:
<request-line>
The HTTP Response format is very similar to the request format:
<status-line>
We can use the principle of HTTP to send requests, and re-consider using socket to send HTTP requests.
The original meaning of Socket is "hole" or "Socket ". Generally referred to as "socket", which is used to describe IP addresses and ports. It is a communication chain handle and can be used to implement communication between different virtual machines or different computers. Hosts on the Internet generally run multiple service software and provide several services at the same time. Each service opens a Socket and binds it to a port. Different ports correspond to different services. In this case, using socket to operate remote files is as easy as reading and writing local files. You just need to use the network cable to transmit local files through hardware.
Therefore, you can consider sending requests as establishing a connection-> opening a socket interface (fsockopen ()-> writing a request (fwrite ()-> reading a response (fread () -> close the file (fclose ()). If you don't talk much about it, go directly to the Code:
<? Php interface Proto {// connect url function conn ($ url); // send get query function get (); // send post query function post (); // close 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 writes the request line protected function setLine ($ method) {$ this-> line [0] = $ method. ''. $ this-> url ['path']. '? '. $ This-> url ['query']. ''. $ this-> version;} // this method writes the header information public function setHeader ($ headerline) {$ this-> header [] = $ headerline ;} // this method writes the subject information protected function setBody ($ body) {$ this-> body [] = http_build_query ($ body );} // connect url public function conn ($ url) {$ this-> url = parse_url ($ url); // judge 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 public function get () {$ this-> setLine ('get') of the get request '); $ this-> request (); return $ this-> response;} // construct the post query data public function post ($ body = array ()) {$ this-> setLine ('post'); // Design content-type $ this-> setHeader ('content-type: application/x-www -Form-urlencoded '); // design the subject information, which is different from GET. $ this-> setBody ($ body ); // calculate content-length $ this-> setHeader ('content-length :'. strlen ($ this-> body [0]); $ this-> request (); return $ this-> response ;}// the public function request () is actually requested () {// put the request line, header information, and object information in an array to facilitate splicing $ req = array_merge ($ this-> line, $ this-> header, array (''), $ this-> body, array (''); // print_r ($ req); $ req = implode (self: CRLF, $ req); // echo $ req; e Xit; fwrite ($ this-> fh, $ req); while (! Feof ($ this-> fh) {$ this-> response. = fread ($ this-> fh, 1024) ;}$ this-> close (); // close the connection} // close the connection public function close () {fclose ($ this-> fh );}}
Use this class to send a simple GET request:
<? Php // remember to reference the Http class $ url = "http://home.jb51.net/u/DeanChopper/"; $ http = new Http ($ url); $ response = $ http-> get (); print_r ($ response );
The returned value is information. You can further process the response information to obtain the desired content.
Let's look at the next specific instance.
<? Php/*** simulate Http post AND get requests using PHP Socket programming * @ author koma */class Http {private $ sp = "\ r \ n "; // double quotation marks must be written here: 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; // Ht Tp 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');} pub Lic 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" * 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 the 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 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/537.36 ',), array ('username' => 'send a Chinese word ', 'age' => 22 ));