当前位置: 动力学知识库 > 问答 > 编程问答 >

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?

网友答案:

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: