PHP HTTP request original acquisition

1. acquisition request line: Method, URI, protocol

Can be obtained from a super variable $ _SERVER, the values ​​of three variables as follows:

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

 

2. Obtain all Header

PHP has a built-in functions getallheader (), is apache_request_headers () function is an alias, all Header HTTP requests may be returned as an array. However, this function can only work in Apache, Nginx or if it was the command line, will be directly reported to the error function does not exist.

The more common method is extracted from the super variable $ _SERVER, the key is the beginning of the relevant Header "HTTP_", you can get all the Header according to this feature.

Specific code 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. Body made

It provides a method for obtaining official request Body, namely:

file_get_contents('php://input') 

 

4. Final complete code as follows:

/** 
* 获取HTTP请求原文 
* @return string 
*/
function get_http_raw() { 
$raw = ''; 
 
// (1) 请求行 
$raw .= $_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\r\n"; 
 
// (2) 请求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) 空行 
$raw .= "\r\n"; 
 
// (4) 请求Body 
$raw .= file_get_contents('php://input'); 
 
return $raw; 
}

 

Guess you like

Origin www.cnblogs.com/tkzc2013/p/10931328.html
Recommended