本文实例讲述了php实现取得http请求的原文的方法,具体步骤如下:
1. 取得请求行:method、uri、协议
可以从超级变量$_server中获得,三个变量的值如下:
$_server['request_method'].' '.$_server['request_uri'].' '.$_server['server_protocol']."rn";
2. 取得所有header
php有个内置函数getallheader(),是apache_request_headers()函数的一个别名,可以将http请求的所有header以数组形式返回。但这个函数只能工作在apache下,如果换了nginx或者命令行,会直接报函数不存在的错误。
比较通用的方法是,从超级变量$_server中提取出来,有关header的键值都是“http_”开头的,可以根据此特点取得所有的header。
具体代码如下:
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
官方提供了一种获取请求body的方法,即:
file_get_contents('php://input')
4. 最终完整代码如下:
/**
* 获取http请求原文
* @return string
*/
function get_http_raw() {
$raw = '';
// (1) 请求行
$raw .= $_server['request_method'].' '.$_server['request_uri'].' '.$_server['server_protocol']."rn";
// (2) 请求headers
foreach($_server as $key => $value) {
if(substr($key, 0, 5) === 'http_') {
$key = substr($key, 5);
$key = str_replace('_', '-', $key);
$raw .= $key.': '.$value."rn";
}
}
// (3) 空行
$raw .= "rn";
// (4) 请求body
$raw .= file_get_contents('php://input');
return $raw;
}
感兴趣的读者可以调试一下本文所述实例,以加深理解。相信对大家的php程序设计有一定的帮助作用。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!