PHP: failed to open stream: HTTP request failed - php

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

Related

lumen- file_get_contents gives error of HTTP_INTERNAL_SERVER_ERROR

In lumen my code is below to send file content in api response , for some document it is working fine but for some document it gives error for HTTP_INTERNAL_SERVER_ERROR
$content = base64_encode(file_get_contents($URL));
Symfony\Component\HttpKernel\Exception\HttpException Object
(
[statusCode:Symfony\Component\HttpKernel\Exception\HttpException:private] => 500
[headers:Symfony\Component\HttpKernel\Exception\HttpException:private] => Array
(
)
[message:protected] => HTTP_INTERNAL_SERVER_ERROR
[string:Exception:private] =>
[code:protected] => 0
[file:protected] => D:\xampp7.1\htdocs\PROJECT_NAME\app\Exceptions\Handler.php
[line:protected] => 76
[trace:Exception:private] => Array
( ...
Is there any solution or required to set php.ini veriable ??
In web error log it gives me error like ,
failed to open stream: HTTP request failed! HTTP/1.1 505 HTTP Version not supported
to resolve this I have get file content with help of below,
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $data[$k]['doc_url']);
$data = curl_exec($ch);
curl_close($ch);
echo"<pre>";print_r($data);die;
it gives me empty output without file contect
I have also add below code
$content = base64_encode(file_get_contents(urlencode($data[$k]['doc_url'])));
$data[$k]['doc_content'] = "$content";
It gives me error of , failed to open stream: No such file or directory in PATH...
Could be that the URL your trying to reach is blocking such ways like you've tried to get contents from their server?
Maybe you should use a CURL with all the relevant settings.
The best way I know to duplicate a request is to open developers console on chrome, then on "Newtork" tab find the request that your trying to mimic. Right click -> Copy -> Copy as CURL (cmd), than paste it here to receive the equivalent PHP CURL code:
https://incarnate.github.io/curl-to-php/
hope it helps, if not, could you expan on the destination you're trying to reach?
good luck
First, you can set context to this kind of request:
$options = array(
'http' => array(
'protocol_version' => '1.0',
'method' => 'GET'
)
);
$context = stream_context_create($options);
Try to get the path to your file like this:
$api = "http://PATH_TO_YOUR_FILE?param=optional_query_params";
$response = file_get_contents($api, false, $context);
Good luck!

Doing a http authentication call with php

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.

Failed to open stream: HTTP request failed - PHP

I have this php code and I'm trying to get content of image.jpg from url but I need to athuraize my self to the server and I did use the fowling code:
$user = 'username';
$pass = 'password';
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode("$user:$pass")
)
));
$data = file_get_contents("http://mysite/User%20Photos/Profile%20Pictures/bmir_LThumb.jpg", false, $context);
My problem still getting this error:
failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized
I saw many situations like me and I tried their solution like this one but still having problem .
Any help ?

Make file_get_contents() return server response despite HTTP errors

If using file_get_contents() to connect to Facebook,
$response = file_get_contents("https://graph.facebook.com/...?access_token=***");
echo "Response: ($response)\n";
And the server returns a non-OK HTTP status, PHP gives a generic error response, and suppresses the response. The body returned is empty.
file_get_contents(...): failed to open stream: HTTP/1.0 400 Bad Request
Response: ()
But if we use cURL, we see that Facebook actually returns a useful response body:
{"error":{"message":"An active access...","type":"OAuthException","code":2500}}
How can I make file_get_contents() return the response body regardless of HTTP errors?
You have to use stream_context_create():
$ctx = stream_context_create(array(
'http' => array (
'ignore_errors' => TRUE
)
));
file_get_contents($url, FALSE, $ctx);
You could ignore the errors file_get_contents throws
$opts = array(
'http'=>array(
'ignore_errors'=> true,
)
);
$context = stream_context_create($opts);
$file = file_get_contents('https://graph.facebook.com/...?access_token=***', false, $context);
var_dump($file);

passing headers into file_get_contents() for a json request

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!

Categories