4

I'm trying to make a GET request using curl in php with the code below.

test.php

$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://apiaddress/collection', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array( 'Authorization: Bearer 374dad6fdc005a0f17c49aeg77rbifuy48t7205hfhf7he8857c' ), CURLINFO_HEADER_OUT => true )); $response = curl_exec($curl); $err = curl_error($curl); $info = curl_getinfo($curl, CURLINFO_HEADER_OUT); $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($err) { echo "cURL Error #:" . $err; } else { echo "Response code: " . $httpCode . "\nResponse body: \n" . $response . "\n"; } curl_close($curl); echo $info; 

This request works in Postman and works using this curl command curl -X GET \ https://apiaddress/collection -H 'Authorization: Bearer 374dad6fdc005a0f17c49aeg77rbifuy48t7205hfhf7he8857c', but when I run php test.php in the cli I get this output. I'm guessing I'm missing a header or sending an incorrect header somewhere?

Response code: 401

Response body:

{"type":"https://apiaddress/errors#error-unauthorized","title":"Unauthorized","detail":"No authorization credentials provided. You must provide an authorization token for this request.","status":401}

GET /collection HTTP/2

Host: apiaddress

Accept: */*

Authorization: Bearer 374dad6fdc005a0f17c49aeg77rbifuy48t7205hfhf7he8857c

3
  • What does $info contain? Commented Feb 12, 2019 at 21:14
  • $info is the output above that starts with GET Commented Feb 12, 2019 at 21:29
  • I too suspect it's an issue with the headers, why not compare the two? You may need to specify Content-Type in your PHP request. Commented Feb 12, 2019 at 21:35

2 Answers 2

3

It turns out that this API requires the User-Agent header and it seems that Postman and the curl cli send those automatically while the php-curl request doesn't. As soon as I added that header and made up a value it started working.

Sign up to request clarification or add additional context in comments.

Comments

2

You appear to be running this under localhost, where you'll additionally need the line:

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 

This tells cURL not to verify your SSL certificate.

Alternatively, if you do indeed have a .pem certificate file, you can use:

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE); curl_setopt($curl, CURLOPT_CAINFO, "/path/to/cacert.pem"); 

1 Comment

I set that flag and it still didn't work. I also hosted the test.php file on an apache server with php and php-curl installed and the same thing happens.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.