Last active
February 11, 2024 18:55
-
-
Save wildiney/b0be69ff9960642b4f7d3ec2ff3ffb0b to your computer and use it in GitHub Desktop.
[deprecated] PHP - How to get and set Bearer Token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* ALERT! There are more than ten years since I wrote the first version (adaptation) of this code with PHP 5.6, | |
* then I changed my code stack and I couldn't mantain this code anymore. Ten years ago worked like a charm. | |
* Fell free to test, use, fork, update, etc. and if possible put in the comments how to fix, | |
* if it doesn't work for you as it is, so other people could find answers. | |
**/ | |
/** | |
* Get hearder Authorization | |
**/ | |
function getAuthorizationHeader(){ | |
$headers = null; | |
if (isset($_SERVER['Authorization'])) { | |
$headers = trim($_SERVER["Authorization"]); | |
} | |
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI | |
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]); | |
} elseif (function_exists('apache_request_headers')) { | |
$requestHeaders = apache_request_headers(); | |
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization) | |
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders)); | |
//print_r($requestHeaders); | |
if (isset($requestHeaders['Authorization'])) { | |
$headers = trim($requestHeaders['Authorization']); | |
} | |
} | |
return $headers; | |
} | |
/** | |
* get access token from header | |
* */ | |
function getBearerToken() { | |
$headers = getAuthorizationHeader(); | |
// HEADER: Get the access token from the header | |
if (!empty($headers)) { | |
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) { | |
return $matches[1]; | |
} | |
} | |
return null; | |
} |
I have problems trying to get the Bearer, it always returns me null
me too bro same error null
I can confirm that these function work in PHP version > 8.0. Although you have a typo on line 34. You need to remove the $this->
.
I used HTTPie to validate the script.
I have problems trying to get the Bearer, it always returns me null
and
me too bro same error null
Did you provide a Auth/Bearer header to your request?
Seems to work great - if your header seems missing from var_dump($_SERVER)
, your HTTP server might be eating up the header - in my case the apache function solved the issue, although I'm not sure yet why that happens.
It worked perfectly, I was having the same issue as @igorsantos07.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this!