How can I access request headers that don't appear in $_SERVER?

半世苍凉 提交于 2019-12-18 11:13:33

问题


I am attempting to create a REST API in PHP and I'd like to implement an authentication scheme similar to Amazon's S3 approach. This involves setting a custom 'Authorization' header in the request.

I had thought I would be able to access the header with $_SERVER['HTTP_AUTHORIZATION'], but it's nowhere to be found in var_dump($_SERVER). The apache_request_headers() function would solve my problem, but my host implements PHP as CGI, so it's unavailable.

Is there another way I can access the complete request headers in PHP?


回答1:


You'll need to do some mod_rewrite wizardry to get your headers past the CGI barrier, like so:

RewriteEngine on
RewriteRule .? - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

<?php
    $auth = $_SERVER['HTTP_AUTHORIZATION'];
?>

Note that if you're using mod_rewrite for other purposes, it could end up being $_SERVER['REDIRECT_HTTP_AUTHORIZATION'].




回答2:


Try

$_ENV['HTTP_AUTHORIZATION']

When using CGI interface instead of Apache Module interface, HTTP headers should be available as environment variables.




回答3:


There is a fantastic PECL extension that allows for all sorts of HTTP related access. PECL_HTTP and more specifically http://php.net/http and http://php.net/manual/en/function.http-get-request-headers.php.



来源:https://stackoverflow.com/questions/827060/how-can-i-access-request-headers-that-dont-appear-in-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!