0

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?

7
  • What cURL version do you have on the web server? Commented Nov 1, 2016 at 16:58
  • if you get a 500, you go look at the server's error log for details. Commented Nov 1, 2016 at 16:59
  • Actually, the statement CURLOPT_HTTPHEADER option is not supported in PHP 5 is false. Commented Nov 1, 2016 at 17:00
  • Who said CURLOPT_HTTPHEADER is not supported by PHP 5? Commented Nov 1, 2016 at 17:01
  • I was looking here. php.net/manual/en/function.curl-setopt.php - "Available since PHP 7.0.7" Commented Nov 1, 2016 at 17:03

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

The problem you are getting is not about CURLOPT_HTTPHEADER. It's been in PHP for ages.

But the new array syntax [] that was added in PHP 5.4.

Change your code to:

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

and it will work fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.