Reputation: 1189
I'm trying to make an API-call from PHP using cURL.
This is my code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/api/");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('sql' => $sql)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: MY-API-KEY'));
$response = curl_exec($ch);
curl_close($ch);
It seems as if the Authorization-header is not set. I've tried to Google around, where some say that the header is not recognized correctly. Can anyone help? My code does work for API-calls without Authorization needed.
UPDATE: Calling the command via the command line tool curl:
curl -H 'Authorization: MY-API-KEY'...
everything works.
My feedback from the PHP cURL is "Access denied".
Upvotes: 1
Views: 4742
Reputation: 694
Because it does't look its constructed properly:
Client side:
When the user agent wants to send the server authentication credentials it may use the Authorization header.
The Authorization header is constructed as follows:
Username and password are combined into a string "username:password" The resulting string is then encoded using the RFC2045-MIME variant of Base64, except not limited to 76 char/line The authorization method and a space i.e. "Basic " is then put before the encoded string. For example, if the user agent uses 'Aladdin' as the username and 'open sesame' as the password then the header is formed as follows:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Upvotes: 1