php getallheaders无法获取自定义头的问题

WBOY
Release: 2016-06-23 13:13:35
Original
905 people have browsed it

在客户端请求的时候增加了自定义的http头,请求如下所示:

自定义http请求头

var_dump(getallheaders);
Copy after login

一开始通过getallheaders参数获取,但是发现在nginx部署的服务器上获取不到,非常奇怪,查看php手册发现getallheaders这个函数只支持apache服务器。于是找到兼容的方法:

if (!function_exists('getallheaders')) {    function getallheaders() {        $headers = array();        foreach ($_SERVER as $name => $value) {            if (substr($name, 0, 5) == 'HTTP_') {                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;            }        }        return $headers;    }}var_dump(getallheaders());
Copy after login

实际上这个方法就是找到$_SERVER变量中以HTTP_开头的属性,对属性做一个字符串替换这样。$_SERVER变量中的HTTP_USER_ID实际就是上面自定义的User-Id:

php中$_SERVER变量

另外关于自定义Http头, 需要注意头的命名规范,不能用下划线命名 ,否则在nginx服务器下读取不到,在查找命名规范的时候,有提到自定义属性用X-开头这个问题。后来查阅了一些资料,发现后来的http协议不建议这样去做。参考地址:

http://stackoverflow.com/questions/3561381/custom-http-headers-naming-conventions

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!