Analysis of PHP Simulating http Request

  • 2021-08-28 19:30:41
  • OfStack

In this paper, an example is given to describe the method of simulating http request by PHP. Share it for your reference, as follows:

In the brief analysis of http, we mentioned a process of browser requesting resources, so can this process be simulated by php? The answer is yes.

php simulates an http request by implementing the following steps:

1. Connect to the apache server

Use fsockopen: Dedicated to connecting to the server and getting 1 connection resource

2. Write to the http protocol

Write content to resources using fwrite

3. Receive data

After the request is successful, the returned data will be stored in the resource

4. Parsing data:

Use fgets, and fgetc functions

Implementation code:


<?php
  //php Simulated emitting http Request 
  //1. Connect to Target Server apache
  $f=fsockopen('localhost',98,$erron,$error);
  //2. Write http Agreement 
  //2.1 Piece together http Agreement 
  // Request line 
  $http="GET /phpstudy/index.php HTTP/1.1\r\n";
  // Request header 
  $http .="Host:localhost\r\n";
  // Blank line 
  $http .="\r\n";
  //2.2 Write to apache Server 
  if(fwrite($f,$http))
  {
    // Write successful 
    //3. Data has been received and stored in f In resources 
    //4. Parsing resources 
    // Cyclic traversal 
    while($line=fgets($f,1024))
    {
      // Output 
      echo $line ."</br>";
    }
  }

For more readers interested in PHP related content, please check the topics on this site: "php socket Usage Summary", "PHP Network Programming Skills Summary", "php Object-Oriented Programming Introduction Tutorial", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "php+mysql Database Operation Introduction Tutorial" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: