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

user1437671 picture user1437671 · Sep 8, 2012 · Viewed 177k times · Source

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 send this as a HTTP REQUEST:

POST /mail/feed/atom/ HTTP/1.1
Host: mail.google.com
Content-length: 0
Content-type: application/json
Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString

I've tried writing a code to send this REQUEST like this:

$crl = curl_init();
$header[] = 'Content-length: 0 
Content-type: application/json';

curl_setopt($crl, CURLOPT_HTTPHEADER, $header);
curl_setopt($crl, CURLOPT_POST,       true);
curl_setopt($crl, CURLOPT_POSTFIELDS, urlencode($accesstoken));

$rest = curl_exec($crl);

print_r($rest);

Not working, please help. :)

UPDATE: I took Jason McCreary's advice and now my code looks like this:

$crl = curl_init();

$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: OAuth '.$accesstoken;

curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
curl_setopt($crl, CURLOPT_POST,true);
$rest = curl_exec($crl);

curl_close($crl);

print_r($rest);

But I'm not getting any output out of this. I think cURL is silently failing somewhere. Please do help. :)

UPDATE 2: NomikOS's trick did it for me. :) :) :) Thank you!!

Answer

Jason McCreary picture Jason McCreary · Sep 8, 2012

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';