Chris Knowles February 2016

Translating cURL request with -G to PHP

I'm trying to use the Facebook Marketing API as detailed in this tutorial.

However I'm stumped with how to translate this suggested cURL command line request into it's PHP equivalent:

curl -G \
-d 'access_token=<ACCESS_TOKEN>' \
https://graph.facebook.com/v2.5/<LEAD_ID>

I would normally do this:

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$access_token);

$result = curl_exec($ch);

But that produces an 'Unsupported post request' error when attempting to run it. I think I am misunderstanding what the '-G' means in the command line version?

Answers


Kenney February 2016

From man curl:

-G, --get

When used, this option will make all data specified with -d, --data, --data-binary or --data-urlencode to be used in an HTTP GET request instead of the POST request that otherwise would be used. The data will be appended to the URL with a '?' separator.

There's no cURL option flag in PHP that directly corresponds to this. You can use

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

or

curl_setopt($ch, CURLOPT_HTTPGET, 'GET');

but this is hardly necessary:

CURLOPT_HTTPGET

TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.

You will have to specify the request parameters differently: instead of setting CURLOPT_POSTFIELDS, append them as a query string to the URL (using urlencode or the equivalent curl_escape if needed):

curl_setopt( $ch, CURLOPT_URL, $url . '?accesstoken='.urlencode('<ACCESS_TOKEN>');

Post Status

Asked in February 2016
Viewed 1,375 times
Voted 13
Answered 1 times

Search




Leave an answer