通过CURL POST JSON数据并抓住它

Wop*_*ppi 4 php json curl

我试图传递一个json数据作为cURL POST的参数.但是,我坚持抓住它并将其保存在db上.

cURL文件:

$data = array("name" => "Hagrid", "age" => "36");                                                                    
$data_string = json_encode($data);                                                                                   

$url = 'http://localhost/project/test_curl';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
                                    'Content-Type: application/json')                                                                                           
                                    );                       
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                                                     

$result = curl_exec($ch);  

//based on http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl
Run Code Online (Sandbox Code Playgroud)

test_curl文件:

    $order_info = $_POST; // this seems to not returning anything

    //SAVE TO DB... saving empty...
Run Code Online (Sandbox Code Playgroud)

我错过了什么?Weew ....

Dav*_*dom 20

您将数据作为原始JSON发送到正文中,它不会填充$_POST变量.

你需要做两件事之一:

  1. 您可以将内容类型更改为将填充$_POST数组的内容类型
  2. 您可以阅读原始身体数据.

如果您可以控制通信的两端,我会建议选项二,因为它会将请求主体大小保持在最小,并随着时间的推移节省带宽.(编辑:我在这里并没有真正强调它将节省的带宽量可以忽略不计,每个请求只有几个字节,这只是一个有效的问题,是非常高的流量环境.但是我仍然建议选项二,因为它是最干净的方式)

在您的test_curl文件中,执行以下操作:

$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);

$postedJson = json_decode($rawData);

var_dump($postedJson);
Run Code Online (Sandbox Code Playgroud)

如果要填充$_POST变量,则需要更改将数据发送到服务器的方式:

$data = array (
  'name' => 'Hagrid',
  'age' => '36'
);

$bodyData = array (
  'json' => json_encode($data)
);
$bodyStr = http_build_query($bodyData);

$url = 'http://localhost/project/test_curl';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Content-Type: application/x-www-form-urlencoded',
  'Content-Length: '.strlen($bodyStr)
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyStr);

$result = curl_exec($ch);
Run Code Online (Sandbox Code Playgroud)

原始的,未解码的JSON现在可用于$_POST['json'].