【问题标题】:Checking for "php://input" AND $_POST检查“php://input”和 $_POST
【发布时间】:2014-08-08 20:51:37
【问题描述】:

我已经看到 good posts about php://input 与 $_POST,但如果我需要同时检查两者,我仍然感到困惑。或者只是检查 php://input。有什么想法吗?

我在这里做的事情是多余的吗?还是必要的?

<?php
    if( $_POST ) {
        // $_POST variables are set, do the stuff
    } else {
        // get php://input
        $php_input = file_get_contents("php://input");

        if( $php_input ) {
            // php input exists, do the stuff
            $php_postdata = json_decode($php_input);

            // ...
        } else {
            // no $_POST and no php://input, so throw an error
            echo 'Error';
            exit();
        }
    }
?>

编辑

我不希望同时使用 $_POST 和 php://input;一个或另一个。用例是我在通过 jQuery 访问 PHP 时得到 $_POST,在通过 AngularJS 访问 PHP 时得到 php://input。

【问题讨论】:

  • 这取决于您希望收到什么样的数据。
  • 你想通过这个方法达到什么目的?虽然您当然可以覆盖默认使用,但在
  • php://inputPUT 请求很有用
  • PHP "php://input" vs $_POST 的可能副本
  • @dave 虽然这个问题很好,但它不是重复的。这个问题旨在专门解决检查两种类型的帖子数据的输入。

标签: php ajax


【解决方案1】:

您的问题是“我需要检查两者还是只检查一个。” This question's answer 准确解释了每一个的内容,以及它们之间的区别。

我们无法知道您需要检查哪一项,但如果您阅读了该问题并得到了答案,您就会知道哪一项拥有您需要的数据。如果您只需要合并两个输入,我们需要知道您希望获得什么样的数据 - 例如,如果它以 application/json 的形式出现,您可以这样做:

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

编辑:知道这是用于角度的,我会用 json_decoded 输入覆盖 $_POST 字段:

if (empty($_POST)) {
    $_POST = json_decode(file_get_contents("php://input"), true));
}

或者让 Angular 以一种将显示在 $_POST 变量中的方式发布数据,a very detailed guide here 解释了如何做到这一点。

【讨论】:

  • 很抱歉给您带来了困惑。是的,我期待 php://input 中的 JSON——特别是来自 AngularJS $http。但我不希望 $_POST 和 php://input 在同一个请求中。我将把问题编辑得更具体。
猜你喜欢
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 1970-01-01
  • 2015-09-02
  • 2021-10-15
  • 2011-08-01
相关资源
最近更新 更多