0

I am trying to retrieve some data from an API that requires authentication via HTTPS. I have the correct authentication, however when using 'file_get_contents' to get the data I am getting the error:

failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

$api_url = 'https://api...';

$client_id = 'user';
$client_secret = 'pass';

$context = stream_context_create(array(
    'http' => array(
        'header' => "Authorization: Basic " . base64_encode("$client_id:$client_secret"),
    ),
));

$result = file_get_contents($api_url, false, $context);

Would there be any particular reason why I am unable to get the data from the authenticated server?

3 Answers 3

1

You're doing the authentication in the right way. The php code is correct.

I think that the problem is the url of request. Because the response return an 400 code, this mean that the authentication works but the request url to API is wrong.

Code 400: Bad request, for example some wrong or missing params in request.

Code 401: unauthorized. (Not you case)

With this infos we can not help you at all. Check url params, read api docs if you can or post more infos about url, or api :)

Byee

Edit Solution:

Check if url has some special char or spaces. Maybe you only need to encode url.

WARNING: Do not encode all url, but only the parameter values.

Example:

 http ://example.com/test?file=This is a file.txt

to:

 http ://example.com/test?file=This%20is%20a%20file.txt
Sign up to request clarification or add additional context in comments.

7 Comments

If I manually copy the url onto my browser and add the authentication parameters I get the data. The request url is correct
Ok, are you sure that the auth is basic?
Yes, the auth is basic
Ok, another thing that you can check is the url. Check if it has some special char or spaces. Maybe you only need to encode url.
You need to encode only the parameters part. Not all url, for example: http ://example.com/test/file?=[this is a file.txt] <- encode part inside brackets
|
1

Http error 400 means "Bad Request".

The remote server is not happy with your request. Maybe you are not building your $context variable correctly.

Comments

0

The value of your header key should be an array containing the headers for the request:

$api_url = 'https://api...';

$client_id = 'user';
$client_secret = 'pass';

$context = stream_context_create(array(
    'http' => array(
        'header' => array("Authorization: Basic " . base64_encode("$client_id:$client_secret"))
                 // ^ check here
    ),
));

$result = file_get_contents($api_url, false, $context);

1 Comment

No, doesn't change anything

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.