How to include Authorization header in cURL POST HTTP Request in PHP?

前端 未结 3 2069
忘掉有多难
忘掉有多难 2020-11-28 07:42

I\'m trying to access mails of a user through Gmails OAuth 2.0, and I\'m figuring this out through Google\'s OAuth 2.0 Playground

Here, they\'ve specified I need to

相关标签:
3条回答
  • 2020-11-28 08:15

    You have most of the code…

    CURLOPT_HTTPHEADER for curl_setopt() takes an array with each header as an element. You have one element with multiple headers.

    You also need to add the Authorization header to your $header array.

    $header = array();
    $header[] = 'Content-length: 0';
    $header[] = 'Content-type: application/json';
    $header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';
    
    0 讨论(0)
  • 2020-11-28 08:16

    use "Content-type: application/x-www-form-urlencoded" instead of "application/json"

    0 讨论(0)
  • 2020-11-28 08:40

    @jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:

    $rest = curl_exec($crl);
    
    if ($rest === false)
    {
        // throw new Exception('Curl error: ' . curl_error($crl));
        print_r('Curl error: ' . curl_error($crl));
    }
    
    curl_close($crl);
    print_r($rest);
    

    EDIT 1

    To debug you can set CURLOPT_HEADER to true to check HTTP response with firebug::net or similar.

    curl_setopt($crl, CURLOPT_HEADER, true);
    

    EDIT 2

    About Curl error: SSL certificate problem, verify that the CA cert is OK try adding this headers (just to debug, in a production enviroment you should keep these options in true):

    curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
    
    0 讨论(0)
提交回复
热议问题