2016-11-01 48 views
0

我正在尝试使用cURL发布一些JSON数据,但我在设置标题时遇到问题。使用cURL在PHP 5中发布JSON数据

我当前的代码看起来像这样:测试使用本地主机(PHP 7)当

$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); 

此代码工作正常。但是,我们的Web服务器仅运行PHP 5,因此不支持CURLOPT_HTTPHEADER选项。

当我将它放在我的代码中时,出现“500内部错误”。 当我将它取出时,我的curl_exec()未运行,并且收到错误消息“失败:”,但没有显示curl_error()

有没有办法设置cURL期望JSON数据没有这个选项?

+0

你在网络服务器上有什么cURL版本? – apokryfos

+0

如果你得到一个500,你会看看服务器的错误日志中的细节。 –

+0

实际上,PHP 5中不支持声明*'CURLOPT_HTTPHEADER'选项*为false。 – apokryfos

回答

1

替换此

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

随着

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

PHP 5.4+支持[]新的数组的语法,但PHP < 5.4需求阵列()溶液中加入

短数组语法支持在PHP 5.4中http://php.net/manual/en/migration54.new-features.php

1

您遇到的问题不是CURLOPT_HTTPHEADER。它已经在PHP多年。

但新增的数组语法[]已在PHP 5.4中添加。

你的代码更改为:

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

,它会正常工作。