php如何获取请求头,做了很多探索。
网上查询的结果只能获取到已定义的字段。
不能获取自定义的字段。
经实验发现自定义字段中不可包含下划线。
去掉下划线,使用$_SERVER就可以获取了。
原因如下:
HTTP头是可以包含英文字母([A-Za-z])、数字([0-9])、连接号(-)hyphens, 也可义是下划线(_)。在使用nginx的时候应该避免使用包含下划线的HTTP头。主要的原因有以下2点。
1.默认的情况下nginx引用header变量时不能使用带下划线的变量。要解决这样的问题只能单独配置underscores_in_headers on。
2.默认的情况下会忽略掉带下划线的变量。要解决这个需要配置ignore_invalid_headers off。
获取请求可以通过$_SERVER获取,如下为示例
1.代码示例
/** * 获取请求header * */ function getallheaders ( $param = null) { $headers = array (); foreach ( $_SERVER as $name => $value ) { if ( substr ( $name , 0, 5) == 'HTTP_' ) { $headers [ str_replace ( ' ' , '-' , ucwords( strtolower ( str_replace ( '_' , ' ' , substr ( $name , 5)))))] = $value ; } } if ( $param != null){ return $headers [ $param ]; } return $headers ; } public function headersdemo() { $param = $this ->request->param(); $a = getallheaders ( $param ); dump( $a ); dump( '===================' ); dump( $_SERVER ); // dump($_SERVER["HTTP_ECOTOKEN"]); // throw new HttpResponseException(json(['code' => 1, 'list' => $param, 'headerss' => $a])); } |
结果示例