【问题标题】:PHP $_POST is empty, but HTTP_RAW_POST_DATA has all dataPHP $_POST 为空,但 HTTP_RAW_POST_DATA 包含所有数据
【发布时间】:2015-01-11 18:00:12
【问题描述】:

我只是想用 JS 向服务器发送 POST 请求。但是服务器有空的$_POST 数组。我可以使用HTTP_RAW_POST_DATA,但它会在 PHP 5.6 中被弃用。我可以在我的$_POST 数组中发布数据吗?

环境:Chrome、apache2、PHP、AngularJS(我正在使用$http.post函数)。

Debug image(很抱歉没有直接附上图片 - 我没有 10 声望)

【问题讨论】:

  • 尝试在 $http.post 中添加标题:{'Content-Type': 'application/x-www-form-urlencoded'}?
  • 查看我的Debug image 获取代码。我试过{'Content-Type': 'application/x-www-form-urlencoded'},但在这种情况下,我在服务器上既没有$_POST,也没有HTTP_RAW_POST_DATA

标签: php json angularjs post


【解决方案1】:

POST 数据必须采用query stringmultipart/form-data 格式才能正确解码。你的数据好像是 JSON,所以你必须自己解码:

$_POST = json_decode(file_get_contents('php://input'), true);

【讨论】:

  • 虽然,要像 $_POST 一样准确地使用它,我们应该将 true 作为第二个参数添加到 json_decode 以便它返回一个数组。 $_POST = json_decode(file_get_contents('php://input'), true);
  • 你是对的。感谢您的评论。答案已编辑。
【解决方案2】:

$_POSTform-urlencodedmultipart/form-data 类型的请求填充。通常它看起来像:

foo=bar&ipsum=lorm

有点像GET 请求。

由于您直接发布 JSON(这太棒了!),您可以使用:

$request_payload = file_get_contents("php://input");

请参阅docs 了解更多信息。

【讨论】:

  • 为什么直接发布 JSON 很棒? (好奇,无意冒犯)
  • 因为对 JSON 数据使用表单编码是有问题的。特别是空值不会被传输。 {"foo":[],"bar:"baz"} 将只产生 bar=baz。表单编码无法指定空数组。
  • 缺少空数组似乎不是问题,因为您可以将其添加为默认值。但是,如果您有:{foo:[[],[]]} 表单编码会给出一个空结果。我认为这是个问题。
【解决方案3】:

默认情况下,jQuery 使用Content-Type: x-www-form-urlencoded 和熟悉的foo=bar&baz=moe 传输数据序列化。然而,AngularJS 使用 Content-Type: application/json{ "foo": "bar", "baz": "moe" } JSON 序列化 传输数据,不幸的是,某些 Web 服务器语言(尤其是 PHP)本身不能反序列化。

所以你可以在定义你的角度模块时这样做:

angular.module('MyModule', [], function($httpProvider) {
    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});

答案来自this post by Felipe Miosso

【讨论】:

  • 是的,它正在工作。但我不知道,为什么在$http.post(filtersUrl, data, {headers: {'Content-Type': 'application/json; charset=utf-8'}) 中直接设置'Content-Type' 不起作用...我做过$http.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8',它也可以工作
  • $http.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8' 也做同样的事情,但我认为在整个应用程序中都可以按照建议提供。
  • 是的,在这种情况下,我需要在我的服务器上执行json_decode(file_get_contents('php://input'));...
【解决方案4】:

看起来像json数据直接发布,不带任何变量试试

$request = file_get_contents('php://input');
print_r($request);

或在发布数据时使用变量,例如

data{'myvar': data}

并且会得到类似的 POST 数据

print_r($_POST['myvar']);

【讨论】:

  • 两者都不起作用:1)file_get_contents("php://input") 给出空字符串; 2){'myvar': data}与原始帖子数据结果相同($_POST为空)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 2013-06-21
  • 2016-06-20
  • 1970-01-01
相关资源
最近更新 更多