BDillan BDillan - 4 years ago 211
PHP Question

PHP HTTP/1.0 400 Bad Request from API Request with authorization headers

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?

Answer Source

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


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.


 http :// is a file.txt


 http ://
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download