PHP implements the method of returning page by imitating socket request

  • 2021-07-26 07:02:00
  • OfStack

In this paper, an example is given to describe the method of PHP to imitate socket request to return to the page. Share it for your reference. The specific implementation method is as follows:

<?php
 $url = "www.XXXX.com";    // Make your own replacement
 $parse = parse_url($url);    // Right URL Parse and return the components.
 $host = $parse['host'];
 $path = $parse['path'];
 $port = 80;
 $timeout = 80;
 $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);    // Open socket Link
 if (!$fp){
     echo $errno."--".$errstr;    // If it is wrong, the error code and error message are returned
 } else {
     $out = "POST $path HTTP/1.1\r\n";    // The following are HTTP Request header information
     $out .= "Host: ".$host."\r\n";
     $out .= "Accept: */*\r\n";
     $out .= "Connection: Close\r\n";
     $out .= "Cookie: $cookie\r\n\r\n";
   
     @fwrite($fp, $out);    // Write the request information to the link
     $status = stream_get_meta_data($fp);
     if(!$status['timed_out']) {    
                 while (!feof($fp)) { 
                     if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {    
                         break;    
                     }    
                 }    
        
                 $stop = false;    
                 while(!feof($fp) && !$stop) {    
                     $data = fread($fp,8192);      //8192 Is the number of bytes that can be returned
                     $return .= $data;        
                 }    
             }    
     fclose($fp);
     print_r($return);
 }

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


Related articles: