HTTP_AUTHORIZATION Missing From Global $_SERVER Variable

Thu 8th July 2021 By David T. Sadler.

I came across an issue where I wanted to read the value of the HTTP_AUTHORIZATION key found in PHP's global $_SERVER variable.

$token = filter_input(INPUT_SERVER, 'HTTP_AUTHORIZATION');

However the value of null was been returned even though a Authorization header was passed as part of the HTTP request.

$ curl 127.0.0.1:8080/bookmarks/add -i -H "Authorization:Bearer xyz" -d "url=http://example.com/2"

A quick print_r($_SERVER) confirmed that there was indeed no item for the key HTTP_AUTHORIZATION hence why I was getting a null value.

However the value was available with the getallheaders function.

$token = getallheaders()['Authorization']);

After a bit of research I found that in some situations Apache may not pass authorization headers to PHP for security reasons. However it is possible to work around this by creating a rewrite rule in the site's .htaccess file to put the authorization header into an environment variable.

<IfModule mod_rewrite.c>
    # Handle Authorization Header.
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

After adding the above to the .htaccess file the HTTP_AUTHORIZATION key is now been populated with the value of the Authorization header.

Links

PHP - Read More Posts.

I don't have comments as I don't want to manage them. You can however contact me at the below address if you want to.

Email david@davidtsadler.com

License

The contents of this site is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Copyright © 2021 David T. Sadler.

Return to Homepage.