How to add curl HTTP Headers for authentication in PHP?

泪湿孤枕 提交于 2019-12-13 04:43:35

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/25407554/how-to-add-curl-http-headers-for-authentication-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!