file_get_contents not working with bearer - php

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);

You can add headers to file_get_contents, it takes a parameter called context that can be used for that:
$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);

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

Your problem maybe for your authorization, do you know about type of authorization in server?
it's possible your type must be cn389ncoiwuencr, say from server about that and try:
'header' => 'Authorization: Bearer cn389ncoiwuencr '.$token

You can use CURL for make a request
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content-Type: application/json en\r\n" .
"Authorization: Token ".$token."\r\n"
)
);
$response = file_get_contents($Base_URL."?format=json", false, stream_context_create($opts));
echo $response;

Related

PHP: Using file_get_contents to access an API - Empty Response

Sorry for the messy code in advance. I want to write a code which returns me infos from the official Blizzard API, which I can then print out on my homepage. The code doesn't throw any errors but it doesn't print out something either. For Starters:
I would also prefer using CURL, but my homepage is on a Wordpress Hosting Site and I don't know how to install the CURL Library that way
allow_furl_open is on
$url = "https://eu.battle.net/oauth/token";
$data = array('grant_type' => 'client_credentials');
//HTTP options
$opts = array('http' =>
array(
'method' => 'POST',
'header' => array ('Content-type: multipart/form-data', 'Authorization: Basic ' .
base64_encode("$client_id:$client_pass")),
'content' => json_encode($data)
)
);
//Do request
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
$accessToken = $json['access_token'];
$tokenURL = "https://us.api.blizzard.com/data/wow/token/?namespace=dynamic-eu";
$opts2 = array('http' =>
array(
'method' => 'POST',
'header' => array('Content-type: multipart/form-data', 'Authorization: Bearer ' . $accessToken),
)
);
$context2 = stream_context_create($opts2);
$json2 = file_get_contents($tokenURL,false,$context2);
$result2 = json_decode($json2, true);
$tokenprice = $result2['price'];
echo "<p>Tokenpreis:" .$tokenprice. "</p>";
I didn't add the $client_id and $client_pass into the code snippet, but this exists obviously. I used this PHP CURL Snippet as template. And this is a short explanation on blizzard's site on how is this supposed to work:
Anyone got any ideas what went wrong? I am really out of ideas here and would love anyone who could help.
Thanks in advance
Based on the curl example from the linked API docs, the content type should be application/x-www-form-urlencoded, and so for the initial request to https://eu.battle.net/oauth/token you should be able to follow the example here.
In your case this will look something like:
$url = 'https://eu.battle.net/oauth/token';
$data = array('grant_type' => 'client_credentials');
$opts = array(
'http' => array(
'method' => 'POST',
'header' => array (
'Content-type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode("$client_id:$client_pass")
),
'content' => http_build_query($data)
)
);
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
Also, in your code you are storing the raw result from the initial request in $json, then the decoded array in $result, but attempting to get the access_token from the initial request, instead of the decoded array.

Cookies are not being sent with file_get_contents or CURL requests

I am trying to send a file_get_contents request to a URL with POST data and a cookie set.
My code is like that:
$postdata = http_build_query(
array(
'search' => 'test',
'token' => '0'
)
);
// Create a stream
$opts = array(
'http'=> array(
'method'=>"POST",
'content' => $postdata,
'header' => "Content-Type: application/x-www-form-urlencoded\n"."Cookie: session_hash=123456789"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('https://example.com', false, $context);
echo $file;
This is posting the data as I can see, but the Cookie is not being sent during the request...
I also tried to use the same request but with CURL and I have the same problem with that.
Any help would be appreciated.
Thanks!
The headers may need to be separated by \r\n rather than just \n. You can also use an array, and they'll be sent properly.
'header' => array("Content-Type: application/x-www-form-urlencoded",
"Cookie: session_hash=123456789")

PHP GET request from an API with a client-id without the usage of cURL

I have to send a GET Request within a PHP Script to get data from an API with a certain given client-id without the usage of cURL.
In the terminal I use following command:
curl -i -u “123456-123ea-123-123-123456789:“-H “Content-Type:
application/json” -X GET
“https://api.aHoster.io/api/rest/jobboards/jobs”
(123456-123ea-123-123-123456789 in this command is the given client-id I got)
Everything works fine in the terminal, but now I like to do this GET request in a php script.
How do I add the client-id in this attempt?
<?php
$url = 'https://api.aHoster.io/api/rest/jobboards/jobs';
$client_id = '123456-123ea-123-123-123456789';
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'GET',
)
);
$context = stream_context_create($options);
$result = #file_get_contents($url, false, $context);
if ($http_response_header[0] == "HTTP/1.1 200 OK") {
//...
} else {
// ...
}
?>
Based on your cURL command you want to add an Authorization header:
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n" .
"Authorization: Basic " . base64_encode($client_id) . "\r\n",
'method' => 'GET',
)
);
I'm not sure but you may need a colon showing empty password "$client_id:".
Also, do a print_r($http_response_header); afterwards as it may contain information such as "Authorization Required" or something else useful.

Dropbox api get access token PHP

I try to get Dropbox access token using PHP,
https://www.dropbox.com/developers-v1/core/docs#request-token
I made 2 php files,
auth.php:
$Header = array(
"Authorization: OAuth oauth_version=\"1.0\", oauth_signature_method=\"PLAINTEXT\", oauth_consumer_key=\"XXX\", oauth_signature=\"XXX&\"\r\n"
);
$Options = array('http' =>
array(
'method' => 'POST',
'header' => $Header,
)
);
$Context = stream_context_create($Options);
$Result = file_get_contents("https://api.dropbox.com/1/oauth/request_token", false, $Context);
echo '<a target="_blank" href="https://www.dropbox.com/1/oauth/authorize?'.$Result.'&oauth_callback=http://localhost/dropbox/access_token.php">auth</a>';
auth.php file is working good! and redirect me to dropbox site to accept me app
but when redirect to access_token.php file, i can't get my access token!
I got error: failed to open stream: HTTP request failed! HTTP/1.1
access_token.php file:
$Options = array('http' =>
array(
'method' => 'POST',
)
);
$au = $_GET['oauth_token'];
$Context = stream_context_create($Options);
$Result = file_get_contents("https://api.dropboxapi.com/1/oauth/access_token?oauth_token=$au", false, $Context);
print_r($Result);
Check selinux setting for httpd_network_connect in Apache. It seems that file get content fails to open the stream.

send POST request in PHP to pushbullet API 401 error

I'm trying to send simple push notifications with pushbullet just through using the email and sending those to the linked account to avoid needing account data. (see reference here: https://docs.pushbullet.com/#pushes)
Therefore I'm using a non cURL-method in php that I (not only) found here:
How do I send a POST request with PHP?
Unfortunately I get back an error as following:
<br />
<b>Warning</b>: file_get_contents(https://api.pushbullet.com/v2/pushes): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
in <b>/path/to/function.php</b> on line <b>42</b><br />
bool(false)
Option to use urls for file_get_contents is set to "on".
My code:
$pushdata = array(
"email" => $email,
"type" => "link",
"title" => "Demo Pushbullet Notification",
"body" => "You have new comment(s)!",
"url" => "http://demo.example.com/comments"
);
//Post without cURL
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n"."Authorization: Bearer <xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>\r\n",
'method' => 'POST',
'content' => http_build_query($pushdata),
),
);
$context = stream_context_create($options);
$result = file_get_contents("https://api.pushbullet.com/v2/pushes", false, $context, -1, 40000);
var_dump($result);
EDIT: Altered the code to christopherhesse's response, still doesn't work. It also shouldn't require access-tokens as I understand that pushing. I understand it as pushing notification from neutral to an linked email. Maybe I'm wrong, but the access-token doesn't fix it.
EDIT(solved): An access-token IS needed to push notifications and as it doesn't work with this method, it does work with cURL.
You need to be using cURL for this so you can pass the API key as a header defined in the documentation: https://docs.pushbullet.com/#http.
<?php
$curl = curl_init('https://api.pushbullet.com/v2/pushes');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer <your_access_token_here>']);
curl_setopt($curl, CURLOPT_POSTFIELDS, ["email" => $email, "type" => "link", "title" => "Demo Pushbullet Notification", "body" => "You have new comment(s)!", "url" => "http://demo.example.com/comments"]);
// UN-COMMENT TO BYPASS THE SSL VERIFICATION IF YOU DON'T HAVE THE CERT BUNDLE (NOT RECOMMENDED).
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
print_r($response);
THIS CODE IS COMPLETELY OFF THE TOP OF MY HEAD AND HASN'T BEEN TESTED
I have broken the options up so you can see them easily but you can combine them into an array and pass them via curl_setoptarray($curl, []);
Sounds like you're missing the access token for your user account. You can find it on https://www.pushbullet.com/account . You should include it in a header like 'Authorization': 'Bearer ACCESS_TOKEN_HERE'.
I know this is an old post but I was having the same problems with sendgrid that uses the same Authorization: Bearer APIKEY method as your website.
I finally got it to work using raw php post using the following code
$url = "your url";
$post_data = 'yourdata';
// Set the headers
$options = array('http' =>
array(
'method' => 'POST',
'header' => "Authorization: Bearer APIKEY\r\n" . 'Content-Type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
// Send the POST data
$ctx = stream_context_create($options);
$fp = fopen($url, 'rb', false, $ctx);
// Read the POST data
$result = json_decode(stream_get_contents($fp));
echo "done";
It seems like switching the order of the header and leaving out the \r\n at the end seemed to work. I spent like an hour on this trying different combinations so I thought I would post this for others.
Note if your using the sendgrid api make sure to set the 'Content-Type: application/json' and make sure your $post_data is in json

Categories