The PHP implementation obtains the original text of the HTTP request

  • 2021-07-13 04:34:47
  • OfStack

In this paper, the example tells the method of obtaining the original text of HTTP request by PHP. The specific steps are as follows:

1. Get the request line: Method, URI, protocol

You can get it from the super variable $_ SERVER, and the values of the three variables are as follows:


$_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\r\n"; 

2. Get all Header

PHP has a built-in function getallheader (), which is an alias for the apache_request_headers () function and returns all Header requested by HTTP as an array. However, this function can only work under Apache. If Nginx or command line is changed, the error that the function does not exist will be reported directly.

The general method is to extract from the super variable $_SERVER, and the key values of Header are all at the beginning of "HTTP_", so all Header can be obtained according to this feature.

The specific code is as follows:


function get_all_headers() { 
$headers = array(); 

foreach($_SERVER as $key => $value) { 
if(substr($key, 0, 5) === 'HTTP_') { 
$key = substr($key, 5); 
$key = strtolower($key); 
$key = str_replace('_', ' ', $key); 
$key = ucwords($key); 
$key = str_replace(' ', '-', $key); 

$headers[$key] = $value; 
} 
} 

return $headers; 
} 

3. Get Body

The official provides a method to obtain the request Body, namely:


file_get_contents('php://input') 

4. The final complete code is as follows:


/** 
*  Get HTTP Original request  
* @return string 
*/ 
function get_http_raw() { 
$raw = ''; 

// (1)  Request line  
$raw .= $_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\r\n"; 

// (2)  Request Headers 
foreach($_SERVER as $key => $value) { 
if(substr($key, 0, 5) === 'HTTP_') { 
$key = substr($key, 5); 
$key = str_replace('_', '-', $key); 

$raw .= $key.': '.$value."\r\n"; 
} 
} 

// (3)  Blank line  
$raw .= "\r\n"; 

// (4)  Request Body 
$raw .= file_get_contents('php://input'); 

return $raw; 
}

Interested readers can debug the examples described in this article under 1 to deepen their understanding. I believe that everyone's PHP programming has a certain help.


Related articles: