Skip to content
Advertisement

file_get_contents not working with bearer

I keep getting this error

Warning: file_get_contents failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

Code

$url = BASE_URL . 'api/v1/users';
$options = array('http' => array(
    'method'  => 'GET',
    'header' => 'Authorization: Bearer '.$token
));
$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);

The middleware i am using with my api accepts the authorization via url parameter or header;

If I use the token in the parameter, it works but not being able to send it via header on the server, cause on localhost its working,

the request is authorized via the bearer token i do not have any username and password to authorize the request with as i demonstrate below i only use a token in my url parameter.

any idea why ? what can i do without changing all my requests to curl

$result = file_get_contents(BASE_URL . 'api/v1/users?authorization='.$token, false);
$response = json_decode($result, true);

Advertisement

Answer

i figured it out it was an apache and php server configuration affecting the header authorization, i was able to override it using .htaccess

i added this line in .htaccess

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement