doushang1964 2014-08-20 14:37
浏览 119
已采纳

如何在PHP中添加curl HTTP Headers进行身份验证?

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条回答 默认 最新

  • duanpi2033 2014-08-20 15:43
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题