mpdc mpdc - 1 month ago 6
JSON Question

POSTing JSON data with cURL in PHP 5

I am attempting to POST some JSON data using cURL, but I'm having an issue setting the headers.

My current code looks like so:

$ch = curl_init('https://secure.example.com');

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
]);

if (!$result = curl_exec($ch))
{
echo 'Failed: ' . curl_error($ch);
curl_close($ch);
die;
}

curl_close($ch);


This code works fine when testing using localhost (PHP 7). However, our web server only runs PHP 5, and as such, the
CURLOPT_HTTPHEADER
option is not supported.

When I keep it in my code, I get a "500 Internal Error".
When I take it out, my
curl_exec()
does not run, and I received the error message "Failed: " but with no
curl_error()
being displayed.

Is there any way to set cURL to expect JSON data without this option?

Answer

Replace this

curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
]);

With

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
));

PHP 5.4+ support the new array syntax of [], but PHP < 5.4 needs array()

Short array syntax support was added in PHP 5.4 http://php.net/manual/en/migration54.new-features.php

Comments