之前记得写过这 2 者的区别, 今天看群里有个朋友也提出了怪异的问题, 说是 "file_get_contents('php://input') 获取不到 curl post 请求的数据的问题"?
其实这并不是所谓的 "怪异", 理解 2 者的区别其实就明白原因啦, 好, 直接举个例子吧, 2 个文件:
1: 发送数据的文件, 如下:
- <?PHP
- $ch = curl_init();
- $data = ['username' => '周伯通', 'password' => '123456','sign'=>'asdfg123456'];
- $url = 'http://xxx.com/fpost.php';//fpost.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('file_get_contents 数据是:'.$res);
- echo'<br> post 数据是:';
- var_dump($_POST);
运行后我们会发现: file_get_contents('php://input') 不能接收 curl post 过来的数组.
解释:
如果 POST 的原始数据是一维数组或 & 拼接的标准格式的键值对字符串, 那么可以用 $_POST 来获取.
如果要通过 file_get_contents 获取, 这种情况下可以发送 JSON 字符串, 用 json_encode 转一下, 或者使用 http_build_query: 比如上面修改如下:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));//POST 数据
结果:
string(97) "file_get_contents 数据是: username=周伯通&password=123456&sign=asdfg123456"
post 数据是: array(3) { ["username"]=> string(9) "周伯通" ["password"]=> string(6) "123456" ["sign"]=> string(11) "asdfg123456" }
所以大家在使用中, 注意下传参的方式即可解决问题. 无非就这 2 种比较常用的数据传参方式啦.
来源: http://www.bubuko.com/infodetail-3138658.html