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

报告相同问题?