SkylarMT SkylarMT - 2 months ago 24
PHP Question

curl -F "data={json:'code'}" in PHP?

I'm trying to access a third-party API with PHP.

Their command reference is like so:

curl "https://api.example.com/api/" \
-H "Authorization: BEARER-TOKEN" \
-F 'data={"language":"EN","latitude":12.345,"longitude":12.345}'


I've tried:

$url = 'https://api.example.com/api/';
$header = array(
'Content-type: application/json',
'Authorization: ' . $bearertoken
);

$fields = 'data={"language":"EN","latitude":"'.$latitude.'","longitude":"'.$longitude.'"}';

// I've tried this too:
$fields = array('data' => '{"language":"EN","latitude":"'.$latitude.'","longitude":"'.$longitude.'"}');

$ch = curl_init();

$options = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
CURLOPT_HTTPHEADER => $header,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_ENCODING => "",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);`


But the server responds with a message telling me it didn't get the parameters I'm sending. When I send the same
-F "data={}"
from a terminal I get the correct response.

Answer

You shouldn't use Content-type: application/json. The value of the data parameter is JSON, but the parameters as a whole are sent in application/x-www-form-urlencoded format.

You also need to URL-encode the value of the data parameter.

The best solution is to use json_encode to create the JSON value, then use an array of post fields, then curl will encode the fields properly.

$header = array(
    'Authorization: ' . $bearertoken
);
$fields = array('data' => 
    json_encode(array('language' => 'EN',
                      'longitude' => $longitude,
                      'latitude' => $latitude)));