search
HomeBackend DevelopmentPHP TutorialDetailed explanation of how PHP uses socket to send HTTP requests

As a PHP programmer, you will definitely be exposed to the http protocol. Only by deeply understanding the http protocol can your programming level improve. Recently, I have been learning about HTTP programming in PHP. Many things suddenly became clear to me and I benefited a lot. Hope to share it with everyone. This article needs to be read by developers with a certain http foundation. I hope to be helpful.

Today I will show you how to use socket to send GET and POST requests.

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 other methods be used to make GET and POST requests? The answer must be yes. Anyone who knows the HTTP protocol knows that the essence of a request submitted by the browser 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. Disconnect.

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 re- Consider 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 the socket interface (fsockopen())->write request (fwrite())->read response (fread()-> ;Close the file (fclose()). Without further ado, let’s go 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 = &#39;&#39;;
  protected $response = &#39;&#39;;
  protected $url = null;
  protected $version = &#39;HTTP/1.1&#39;;
  protected $fh = null;
  protected $line = array();
  protected $header = array();
  protected $body = array();
  public function __construct($url) {
    $this->conn($url);
    $this->setHeader(&#39;Host: &#39; . $this->url[&#39;host&#39;]);
  }
  // 此方法负责写请求行
  protected function setLine($method) {
    $this->line[0] = $method . &#39; &#39; . $this->url[&#39;path&#39;] . &#39;?&#39; .$this->url[&#39;query&#39;] . &#39; &#39;. $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[&#39;port&#39;])) {
      $this->url[&#39;port&#39;] = 80;
    }
    // 判断query
    if(!isset($this->url[&#39;query&#39;])) {
      $this->url[&#39;query&#39;] = &#39;&#39;;
    }
    $this->fh = fsockopen($this->url[&#39;host&#39;],$this->url[&#39;port&#39;],$this->errno,$this->errstr,3);
  }
  //构造get请求的数据
  public function get() {
    $this->setLine(&#39;GET&#39;);
    $this->request();
    return $this->response;
  }
  // 构造post查询的数据
  public function post($body = array()) {   
    $this->setLine(&#39;POST&#39;);
    // 设计content-type
    $this->setHeader(&#39;Content-type: application/x-www-form-urlencoded&#39;);
    // 设计主体信息,比GET不一样的地方
    $this->setBody($body);
    // 计算content-length
    $this->setHeader(&#39;Content-length: &#39; . strlen($this->body[0]));
    $this->request();
    return $this->response;
  }
  // 真正请求
  public function request() {
    // 把请求行,头信息,实体信息 放在一个数组里,便于拼接
    $req = array_merge($this->line,$this->header,array(&#39;&#39;),$this->body,array(&#39;&#39;));
    //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.***.net/u/DeanChopper/";
$http=new Http($url);
$response=$http->get();
print_r($response);

The return value is information, which can be used to respond The information is further processed to get what 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 = &#39;HTTP/1.1&#39;;
  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[&#39;Host&#39;] = $this->urlinfo[&#39;host&#39;];
    return $this;
  }
   
  public function get($header = array()) {
    $this->header = array_merge($this->header, $header);
    return $this->request(&#39;GET&#39;);
  }
   
  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[&#39;Content-Type&#39;] = &#39;application/x-www-form-urlencoded&#39;;
      $this->header[&#39;Content-Length&#39;] = strlen($this->body);
    }
    return $this->request(&#39;POST&#39;);
  }
   
  private function request($method) {
    $header = "";
    $this->requestLine = $method.&#39; &#39;.$this->urlinfo[&#39;path&#39;].&#39;?&#39;.$this->urlinfo[&#39;query&#39;].&#39; &#39;.$this->protocol;
    foreach ( $this->header as $key => $value ) {
      $header .= $header == "" ? $key.&#39;:&#39;.$value : $this->sp.$key.&#39;:&#39;.$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[&#39;port&#39;]) ? isset($this->urlinfo[&#39;port&#39;]) : &#39;80&#39;;
    $this->fp = fsockopen($this->urlinfo[&#39;host&#39;], $port, $errno, $errstr);
    if ( !$this->fp ) {
      echo $errstr.&#39;(&#39;.$errno.&#39;)&#39;;
      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.***.com/14/1102/01/AA0PFA7Q00014AED.html";
$url = "http://localhost/httppro/post.php";
$http = Http::create()->init($url);
/* 发送get请求 
echo $http->get(array(
  &#39;User-Agent&#39; => &#39;Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36&#39;,
));
*/
 
/* 发送post请求 */
echo $http->post(array(
    &#39;User-Agent&#39; => &#39;Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36&#39;,
), array(&#39;username&#39;=>&#39;发一个中文&#39;, &#39;age&#39;=>22));

Related recommendations:

Detailed explanation of PHP's file permission modification function chmod

Detailed explanation of how PHP implements the Hook mechanism

Detailed explanation of using PHP to find the longest common substring of two strings

The above is the detailed content of Detailed explanation of how PHP uses socket to send HTTP requests. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools