I need to pass these headers into the $context variable, i tried using putting the values into an array and then passing it into stream_context_create() function but i get http warnings from the file_getcontents function
$prod_id = 4322;
$tnxRef = "RT45635276GHF76783AC";
$mackey = "ADECNH576748GH638NHJ7393MKDSFE73903673";
$agent = $_SERVER['HTTP_USER_AGENT'];
$hash = hash('SHA512', $prod_id.$txnRef.$mackey);
$headers = array(
'http'=>(
'method'=>'GET',
'header'=>'Content: type=application/json \r\n'.
'$agent \r\n'.
'$hash'
)
)
stream_context_create($headers)
$url_returns = file_get_contents("https://test_server.com/test_paydirect/api/v1/gettransaction.json?productid=$prod_id&transactionreference=$txnRef&amount=$amount", false, $context);
$json = json_decode($url_returns, true);
Error:
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request`
Thats the error i get, can somebody please help with a definitive example.
You have several errors in your code.
The server returns 400 Bad Request, because your code would result in this incorrect HTTP request:
GET /test_paydirect/api/v1/gettransaction.json?productid=4322&transactionreference=RT45635276GHF76783AC&amount= HTTP/1.1
Host: test_server.com
Content: type=application/json
$agent
$hash
The errors are:
Variable expressions are not evaluated within single quotes
$amount is not set in your code example
The header is Content-Type: and not Content: type=
All headers (agent, hash) must have their corresponding name
Here is an example that should work:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'agent' => $agent,
'header' => "Content-Type: application/json\r\n"
. "X-Api-Signature: $hash"
)
)
);
Please note: X-Api-Signature is just an example - it depends on the API you are using how the API key header is named and how the hash is calculated. You should find this information in the Docs of your API!
Related
I already tried the following but it doesn't seem to work:
file_get_contents('http://username:password#example.com/requested.file');
And
$auth = base64_encode("username:password");
$context = stream_context_create(['http' => ['header' => "Authorization: Basic $auth"]]);
$homepage = file_get_contents("http://example.com/requested.file", false, $context );
I still keep getting a failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized.
I checked multiple times that the userdata I try to log in with is correct.
I have the script below and was wondering why I was getting the error:
failed to open stream: HTTP request failed! HTTP/1.1 401 Authorization Required
The base64 encoded value is in the form username:password and is correct. The API documentation gave the example as:
Authorization: Basic
QWxhZGRpbjpvcGVuIHNlc2FtZQ==
For example, if the user agent uses Aladdin as the username and open sesame as the password, then the field is formed as above in the HTTP header
<?php
$postData = array(
'primaryContact' => array('id' => 1),
'subject' => 'Something not working'
);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=\r\nContent-Type: application/json",
'content' => json_encode($postData)
)
));
// Send the request
$response = file_get_contents('http://127.0.0.1/', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData;
?>
Any ideas?
Tested and your code works. i think its the server. atleast check the server username and password again (your base64 code is correct)
I tested on: iis 7.5 the website has basic auth setup (http 401 Challenge)
(on iis that means that i can use my windows server credentials)
add the $http_response_headers to your error line to get more information.
// Check for errors
if($response === FALSE){
var_dump($http_response_header);
die('Error');
}
As the title says I’m having trouble making a signed HTTP request for an OAuth 1.0a protected file.
I am trying to use the file_get_contents method for the request an want to add the Authorization header by using the stream_context_create() method. [Sourcecode below]
$url = "https://rest.immobilienscout24.de/restapi/api/offer/v1.0/user/me/realestate";
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: OAuth
oauth_consumer_key = \"MY_KEY\”,
oauth_token = \"MY_TOKEN\"
oauth_signature_method= \"HMAC-SHA1\",
oauth_timestamp=\"TIMESTAMP\",
oauth_nonce=\"MY_NONCE\",
oauth_signature=\"MY_SIGNATURE\""
)
));
$data = file_get_contents($url, false, $context);
This is how the request should look like
GET /api/file HTTP/1.1 Host: example.com
Authorization: OAuth oauth_consumer_key="KEY",
oauth_token="TOKEN",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="TIMESTAMP",
oauth_nonce="NONCE",
oauth_signature="SIGNATURE"
Problem: I always get the following Error:
failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in line XX.
What am I doing wrong? Is it creating the header?
I know this can be done with curl also but I have literally no knowledge nor experience using curl.
Thank you for your help!
According to the OAuth 1.0a spec
The OAuth Protocol Parameters are sent in the Authorization header the following way:
Parameter names and values are encoded per Parameter Encoding.
For each parameter, the name is immediately followed by an '=' character (ASCII code 61), a '"' character (ASCII code 34), the parameter value (MAY be empty), and another '"' character (ASCII code 34).
Parameters are separated by a comma character (ASCII code 44) and OPTIONAL linear whitespace per [RFC2617].
The OPTIONAL realm parameter is added and interpreted per [RFC2617], section 1.2.
One issue is that you're inserting \n (LF) characters into your header string, which isn't allowed according to RFC2617. You also seem to be missing a comma after you oauth_token. It's also unclear if you're properly encoding your parameters.
I think an easier way to avoid making these mistakes could be to either use something like http_build_query and pass PHP_QUERY_RFC3986 as the enc_type paremeter to be compliant with RFC3986, which is what OAuth 1.0a states it follows, or you could just set the parameters in a separate array and array_map to encode them yourself.
$params = [
"realm" => $realm, /* optional */
"oauth_consumer_key" => $key,
"oauth_token" => $token,
"oauth_signature_method" => $sigmeth,
"oauth_timestamp" => $timestamp,
"oauth_nonce" => $nonce,
"oauth_signature" => $sig,
];
option 1
/* This will give you the proper encoded string to include in your Authorization header */
$params = http_build_query($params, null, ',', PHP_QUERY_RFC3986);
$opts = ["http" => ["header" => "Authorization: OAuth " . $params]];
$context = stream_context_create($opts);
$data = file_get_contents($url, false, $context);
option 2
$params = implode(',',array_map(function($v,$k) {
return $k . '="' . rawurlencode($v) . '"';
}, $params, array_keys($params)));
$opts = ["http" => ["header" => "Authorization: OAuth " . $params]];
$context = stream_context_create($opts);
$data = file_get_contents($url, false, $context);
I think option 2 is actually more compliant with OAuth 1, because http_build_query won't quote the parameters. rawurlencode will be compliant with RFC3986 which should help keep your values properly encoded.
When I debug a site via Chrome browser I get JSON response. But when I try to do this via PHP I get an error message.
failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found
Thanks for any help.
For example:
Things to do in Chrome:
Go to page: http://gruper.pl/warszawa and on the bottom you will see a button "Wiecej ofert". After click you will see in a debug:
http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1
and response:
[{"ID_PAGE":"59199","ID_CITY":"3952","main_city":"3952","date_start":"2014-02-23 18:00:00","date_end":"2014-03-01 23:59:00","price".....
Is there any possibility to get the same in PHP?
My code is:
<?php
$url = 'http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1';
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Accept:application/json\r\n" .
"Accept-Encoding:gzip,deflate,sdch\r\n" .
"X-Requested-With:XMLHttpRequest\r\n",
'method' => 'GET'
),
);
$context = stream_context_create($options);
$result = (file_get_contents($url, false, $context));
?>
<html>
<head>
<meta charset="UTF-8">
</head>
</html>
It looks like that URL will return a 404 HTTP status code unless these headers are set:
X-Requested-With: XMLHttpRequest
Referer: http://gruper.pl/warszawa
So this will work:
<?php
$url = 'http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1';
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "X-Requested-With: XMLHttpRequest\r\n" .
"Referer: http://gruper.pl/warszawa"
)
);
$context = stream_context_create($options);
$result = (file_get_contents($url, false, $context));
echo $result;
?>
Need to request some code two times in my app. Fist request url as ajax call, and also need to request this url in controller (something like hmvc). I know how to develop this via curl but I found another kind of idea how to implement this, just use function file_get_contents with before prepared params. This my code:
// Setup limit per page
$args['offset'] = $offset;
$args['limit'] = $this->_perpage;
// --
// Convert search arguments to the uri format
$data = http_build_query($args);
// Define request params
$options = array(
'http' => array(
'header' => 'Content-type: application/json' . PHP_EOL .
'Content-Length: ' . strlen($data) . PHP_EOL,
'method' => 'POST',
'content' => $data,
),
);
$context = stream_context_create($options);
$result = file_get_contents(
'http://'.$_SERVER['HTTP_HOST'].'/search/items', FALSE, $context
);
Request method was detected ok in requested uri, but params wasn't passed. Why this is not pass arguments to request? Where is bug in my code? Many thanks for any answers.
http_build_query builds application/x-www-form-urlencoded content. (not application/json)
There is a full example:
How to post data in PHP using file_get_contents?
Content type should be application/x-www-form-urlencoded. If you want to stay with application/json, try to get posted data using file_get_contents("php://input").