21
Apr
2014
Getting Raw HTTP Request in PHP
In case you ever want to get a raw HTTP request for logging, analysis or filtering reasons, the code is simply:
function http_raw_request(){
$http_request = "";
foreach (getallheaders() as $key => $value){
$http_request .= $key . ': ' . $value . "\n";
}
$http_request .= "\n";
$http_request .= file_get_contents("php://input");
return $http_request;
}
If, like me, you use php-fastcgi and lack the function getallheaders, it can be implemented as followslink:
if (!function_exists('getallheaders')){
function getallheaders(){
$headers = '';
foreach ($_SERVER as $name => $value){
if (substr($name, 0, 5) == 'HTTP_'){
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
Example capture on a comment for this blog:
Host: heapspray.net + User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1+ Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 + Accept-Language: en-us,en;q=0.5 + Accept-Encoding: gzip, deflate + Connection: keep-alive + Referer: http://heapspray.net/post/added-comments/ + Content-Type: application/x-www-form-urlencoded + Content-Length: 38 + + id=46&poster=test&email=test&text=test
Very useful for anything from site statistics to debugging and filtering spam (most spambots have very different request headers than most browsers).