Home > Article > Backend Development > PHP uses socket to send HTTP requests (GET, POST), socketget_PHP tutorial
Today I will show you how to use socket to send GET and POST requests. I will use an Http class encapsulated by Teacher Yan Shiba to illustrate.
In daily programming, I believe that many people, like me, use the browser to make GET and POST requests to the server most of the time. So, can I use other methods to make GET and POST requests? The answer must be yes. Anyone who knows the HTTP protocol knows that the essence of the browser submitting a request is to send a request information to the server. This request information consists of a request line, a request header, and a request body (optional). The server returns a response information based on the request information. The connection is lost.
The format of the HTTP request is as follows:
<request-line> <headers> <blank line> [<request-body>]
The format of the HTTP response is very similar to the format of the request:
<status-line> <headers> <blank line> [<response-body>]
We can use the principle of HTTP to send requests, and we can reconsider using sockets to send HTTP requests.
The original English meaning of Socket is "hole" or "socket". Also commonly called a "socket", it is used to describe an IP address and port. It is a handle to a communication chain 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 is bound to a port. Different ports correspond to different services. From this point of view, it is actually as easy to use sockets to operate remote files as to read and write local files. Think of local files as being transmitted through hardware, and remote files as long as they are transmitted through network cables.
Therefore, sending a request can be considered as establishing a connection ->open socket interface (fsockopen())->write request (fwrite())->read response (fread()->close file (fclose()). Without further ado, let’s get straight to the code:
<?php interface Proto { // 连接url function conn($url); //发送get查询 function get(); // 发送post查询 function post(); // 关闭连接 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']); } // 此方法负责写请求行 protected function setLine($method) { $this->line[0] = $method . ' ' . $this->url['path'] . '?' .$this->url['query'] . ' '. $this->version; } // 此方法负责写头信息 public function setHeader($headerline) { $this->header[] = $headerline; } // 此方法负责写主体信息 protected function setBody($body) { $this->body[] = http_build_query($body); } // 连接url public function conn($url) { $this->url = parse_url($url); // 判断端口 if(!isset($this->url['port'])) { $this->url['port'] = 80; } // 判断query if(!isset($this->url['query'])) { $this->url['query'] = ''; } $this->fh = fsockopen($this->url['host'],$this->url['port'],$this->errno,$this->errstr,3); } //构造get请求的数据 public function get() { $this->setLine('GET'); $this->request(); return $this->response; } // 构造post查询的数据 public function post($body = array()) { $this->setLine('POST'); // 设计content-type $this->setHeader('Content-type: application/x-www-form-urlencoded'); // 设计主体信息,比GET不一样的地方 $this->setBody($body); // 计算content-length $this->setHeader('Content-length: ' . strlen($this->body[0])); $this->request(); return $this->response; } // 真正请求 public function request() { // 把请求行,头信息,实体信息 放在一个数组里,便于拼接 $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(); // 关闭连接 } // 关闭连接 public function close() { fclose($this->fh); } }
Use this class to send a simple GET request:
<?php //记得引用Http类 $url="http://home.jb51.net/u/DeanChopper/"; $http=new Http($url); $response=$http->get(); print_r($response);
The return value is information. You can further process the response information to get the content you want.
Let’s look at the next specific example
<?php /** * 使用PHP Socket 编程模拟Http post和get请求 * @author koma */ class Http{ private $sp = "\r\n"; //这里必须要写成双引号 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对象单例 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; } /* * 注意:这里的fsockopen中的url参数形式为"www.xxx.com" * 不能够带"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); /* 发送get请求 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', )); */ /* 发送post请求 */ 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'=>'发一个中文', 'age'=>22));