[英]Why is php curl not working with application/json posting?
我在远程服务器 (www.oneofmysites.com/hitme.php) 上有一个文件,其中包含:
<?php
$d = array(
'test' => 1,
'request' => $_REQUEST,
'post' => $_POST,
'get' => $_GET,
'server' => $_SERVER,
'session' => $_SESSION,
);
print '<pre>';
print_r($d);
换句话说,它只是打印出一堆变量。 我用它来测试我发送到那里的帖子。 我这样做如下:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('!!THIS_IS_GREAT!!' => 'VERY VERY GREAT!!!')));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$server_output = curl_exec($ch);
curl_close ($ch);
print $server_output;
如果我像这样运行代码,注释掉“application/json”行,那么它返回值:
Array
(
[test] => 1
[request] => Array
(
[!!THIS_IS_GREAT!!] => VERY VERY GREAT!!!
)
[post] => Array
(
[!!THIS_IS_GREAT!!] => VERY VERY GREAT!!!
)
[get] => Array
(
)
但是当我添加这一行时:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
然后帖子返回:
Array
(
[test] => 1
[request] => Array
(
)
[post] => Array
(
)
[get] => Array
(
)
我做错了什么会导致这些值无法通过? 我必须以某种方式专门启用 json 发布吗? (我对此表示怀疑,因为我已经在 2 个不同的服务器上尝试过)。
我错过了什么?
更新
我自己发现我必须使用它:
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
这对我来说不起作用是没有意义的:
$_POST
但这确实:
file_get_contents("php://input")
如果有人知道原因,请分享。
没有记录任何超全局变量来解析 JSON。 特别地, $ _ POST被描述为:
当使用
application/x-www-form-urlencoded
或multipart/form-data
作为请求中的 HTTP Content-Type 时,通过 HTTP POST 方法传递给当前脚本的关联变量数组。
您可以使用php://input流包装器(例如使用file_get_contents() )检查原始 POST 数据,您可以使用json_decode()解码 JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.