Andy
Andy

Reputation: 23

Authenticated curl not working in php

I am trying to create a simple PHP script that calls two different REST APIs on two different domains. Both services are HTTPS and require authentication. When I do a curl from the terminal, I get the response in JSON for both domains and everything works beautifully:

curl --user “myuser:mypassword” https://www.example.com/rest/api/2/projects

Notice that it's a GET, not a POST.

The strange thing is that when I try the exact same curl commands from my PHP script neither of them works.

This what happens:

Here's what's NOT happening:

Even if put in a bad username or password, both services will act exactly the same way.

To me what's suspicious is that both domains don't authenticate my calls which makes me think there's either a problem with my code or in the php curl library.

Here's my code:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $link3); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
$encodedAuth = base64_encode($username.":".$password);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authentication : Basic ".$encodedAuth));
curl_setopt($curl, CURLOPT_USERPWD, $username.":".$password);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);   //get status code

I know some of it is redundant, but I wanted to try everything and nothing works. Any ideas?

My environment:

Upvotes: 2

Views: 706

Answers (1)

Hans Z.
Hans Z.

Reputation: 53978

The current code mixes various approaches and does it in a conflicting way:

  • the authentication header is named Authorization: and not Authentication:
  • the CURLOPT_HTTPAUTH, CURLAUTH_ANY tries to negotiate with the server and it shouldn't (neither does the working cURL command line)

Just use:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $link3);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, $username.":".$password);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);
# for debugging/non-prod
#curl_setopt($curl, CURLOPT_VERBOSE, true);
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
curl_close($curl);
echo $result;

Upvotes: 2

Related Questions