![](/img/trans.png)
[英]Why is php curl not working with application/json posting?
[英]Why is posting JSON with PHP Curl not working?
我有以下 function:
function postCurl($url, $data){
$data = json_encode($data);
$ch = curl_init( $url);
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec( $ch );
curl_close( $ch );
return $result;
}
此 function 将(多维)数组转换为 JSON 应将其与 curl 一起发布。
请求的 url 简单地返回所有 post 值:
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
我用 Postman 验证请求的 url 正在工作,但是当我通过 curl 发帖时,我没有得到任何结果。 我可以用 Postman 复制这个问题的唯一方法是发送不正确的 JSON 所以我绕过了json_encode
function 并尝试了一个有效的 JSON 字符串但没有结果。
我过去曾使用过这个 function,所以我认为这一定是设置问题。
任何帮助,将不胜感激。
我在这个链接的帮助下发现了问题:
file_get_contents('php://input') 总是返回一个空字符串
因为我使用curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
我看不到有从www.url.com到 url.com 的重定向。
重定向请求时,您会丢失file_get_contents("php://input")
中的所有数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.