Dead lock
Dead lock

Reputation: 33

How to add curl HTTP Headers for authentication in PHP?

I want to add the HTTP headers for authenticating Udemy API access.Can someone tell me as to how to add the headers.I already have the client id and secret key.I want to access the API from a PHP page. https://developers.udemy.com/ Here is the code i tried using:

$ch = curl_init($request);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id:MY_ID','X-Udemy-Client-Secret:Secret'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$results= curl_exec($ch);
echo $results;

Output:

Blank Page

Can someone point out what the problem might be?

Upvotes: 0

Views: 3684

Answers (1)

hindmost
hindmost

Reputation: 7205

As @drmarvelous wrote, you perform two requests (1st - by CURL, and 2nd - by file_get_contents) which does the same. Wherein the result of CURL request is not actually used in your script. It use the result of file_get_contents request which is performed without authentication parameters. Because of this you getting Unauthorized error.

So you have to use the result of CURL request:

...
$json = json_decode($results, true);
print_r($json);

Update:

You have to ensure you use valid URL for API request, i.e. value of $request in your code should be valid URL. Also, ensure you pass valid authentication parameters (Client-Id and Client-Secret) by HTTP headers.

Furthermore, since API is secured, you have to disable SSL peer verification by setting CURLOPT_SSL_VERIFYPEER option to false.

So the code should look like this:

$ch = curl_init($request);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id: {YourID}','X-Udemy-Client-Secret: {YourSecret}'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$results= curl_exec($ch);
echo $results;

Upvotes: 2

Related Questions