file_get_contents('php://input')获取不到Curl POST的数据

17-10-01 12:55 字数 815 阅读 9893 已编辑

今天遇到了一个file_get_contents('php://input')获取不到curl post请求的数据的问题。
代码如下:
两个php脚本
1.php

$ch = curl_init();    

$data = json_encode(array('username' => 'aaa', 'password' => 'xxx','sign'=>'dasddsadxf123dsad'));    

$url = 'http://test.com/test_php/file_get_contents_post/2.php';    
$ch = curl_init(); //初始化curl    
curl_setopt($ch, CURLOPT_URL, $url);//设置链接    
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息    
curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式    
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//POST数据    
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");    
$response = curl_exec($ch);//接收返回信息    
if(curl_errno($ch)){//出错则显示错误信息    
    print curl_error($ch);    
}    
curl_close($ch); //关闭curl链接    
echo $response;//显示返回信息    

2.php

$res = file_get_contents('php://input');    
var_dump($res);    

返回结果为空,在1.php里打印返回结果,获取不到2.php返回的内容。请问是什么原因?有人知道吗?

1人点赞>
关注 收藏 改进 举报
1 条评论
排序方式 时间 投票
Up骚年

file_get_contents('php://input')不能接收curl post过来的数组。
如果POST的原始数据是一维数组或&拼接的标准格式的键值对字符串,用$_POST来获取。
这种情况下你可以发送json字符串,用json_encode转一下,然后在2.php就能接收到啦。

请登录后发表评论