Skip to content

Instantly share code, notes, and snippets.

@wildiney
Last active February 11, 2024 18:55
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save wildiney/b0be69ff9960642b4f7d3ec2ff3ffb0b to your computer and use it in GitHub Desktop.
Save wildiney/b0be69ff9960642b4f7d3ec2ff3ffb0b to your computer and use it in GitHub Desktop.
[deprecated] PHP - How to get and set Bearer Token
<?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;
}
@jeremyikwuje
Copy link

Thanks for this!

@poostmaan
Copy link

I have problems trying to get the Bearer, it always returns me null

@ombozdemir
Copy link

ombozdemir commented Oct 24, 2022

me too bro same error null

@LouisOuellet
Copy link

LouisOuellet commented Oct 31, 2022

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?

@igorsantos07
Copy link

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.

@HeroDjou
Copy link

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