PHP implements the retrieval of the original HTTP request ,. PHP implements the retrieval of the original HTTP request. This article describes how PHP implements the retrieval of the original HTTP request. the specific steps are as follows: 1. obtain the request line: Method, URI, and protocol can be used to obtain the original text of the HTTP request from the PHP super,
This example describes how to obtain the original HTTP request using PHP. the specific steps are as follows:
1. get the request line: Method, URI, protocol
You can obtain the value from the super variable $ _ SERVER. the values of the three variables are as follows:
$_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\r\n";
2. retrieve all headers
PHP has a built-in function getallheader (), which is an alias of the apache_request_headers () function. all headers of the HTTP request can be returned in an array. However, this function can only work in Apache. if Nginx or command line is changed, an error that does not exist will be reported directly.
The common method is to extract from the super variable $ _ SERVER. the key values of headers start with "HTTP _". you can obtain all headers based on this feature.
The 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 the Body
The official website provides a method to obtain the request Body, namely:
file_get_contents('php://input')
4. the complete code is as follows:
/*** Get the original HTTP 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) empty row $ raw. = "\ r \ n"; // (4) request Body $ raw. = file_get_contents ('php: // input'); return $ raw ;}
Interested readers can debug the examples described in this article to deepen their understanding. I believe it will be helpful for everyone's PHP programming.
Example, this article describes how PHP can obtain the original HTTP request. the specific steps are as follows: 1. get the request line: Method, URI, protocol can be exceeded...