Authorization header is not set with PHP cURL

868

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".

913

Answer

Solution:

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==

People are also looking for solutions to the problem: php - Right way to escape string after replacing quotes?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.