PHP:INPUT_POST(用于filter_input_array)覆盖$ _POST之前的所有修改

在下面这个代码中,PHP的INPUT_POST参数:

filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

似乎覆盖了filter函数应用于 superglobal $POST 的所有修改。

测试:

<?php
// 1.
$_POST['abc'] = '123';
var_dump($_POST);

// 2.
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
var_dump($_POST);
?>

输出:

在 // 2之后,$POST 将为空(因为初始 POST 为空)。

index.php:4:
array (size=1)
'abc' => string '123' (length=3)

index.php:8:null

所以一定要把 $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING, true); 放在你的脚本上!

问:有没有人注意过这个细节?——或者我在推理上犯了错误?

可能的答案:这可能是因为数据来源于 $_REQUEST 而不是 $_POST

Your variable $_POST contains null after that function is executed and assigned to $_POST. From the PHP Manual, null may be returned because the resource on which the function is supposed to work is not defined.

I believe you should investigate either the integrity of your variables or your use of that function.

There is no direct connection between $_POST, and INPUT_POST.

The latter only specifies that filter_input_vars should get the data to filter from the same source as was used to fill $_POST initially. Later manipulation of $_POST does not change what POST data was send to the script originally.

You can easily verify this by setting up a little form that posts a hidden input field to your script. Then add an additional entry to $_POST in that script, as you did in your example above. You will see that filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING) returns an array that contains the entry for the hidden field, but not one for the entry you added to $_POST manually.

That http://php.net/manual/en/filter.constants.php describes INPUT_POST as “POST variables” and links to the description of $_POST might be a little bit misleading here, granted. But to be fair, it says POST there, and not $_POST.

so be sure, to put $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING, true); on the top of your scripts!

I would not really recommend that. Every PHP developer will assume that $_POST contains unfiltered data. As soon as you f.e. start using 3rd-party modules, that might lead to trouble.

Leaving $_POST as it is, and using a separate variable to hold your filtered POST parameters, is the better way to go IMHO.