PHP:有一种安全的方法可以提取($ _POST)
是否存在一种安全的方法来自动分配发布的数组中的键?以下是两个错误方法的示例...
Is there a safe way to auto assign the keys in a posted array? Below are two examples of wrong ways...
foreach( $_POST as $key => $value ) {
$$key = $value;
}
或
extract($_POST)
有没有更好的方法,还是最好编写代码:
Is there a better way, or is it best to code:
$foo = $_POST('foo');
$bar = $_POST('bar');
....
我表格上的所有50个输入?
for all 50 inputs on my form?
(发布的信息将插入数据库中).
(the posted info will be inserted into a database).
一次提取所有输入字段的另一种谨慎方法是:
One more cautious way of extracting all input fields at once is:
extract( $_POST, EXTR_OVERWRITE, "form_" );
这样,您的所有输入变量将至少被称为$form_foo
和$form_bar
.避免在全局范围内执行此操作-不是因为global是邪恶的,而是因为没有人在这里进行清理.
This way all your input variables will be called $form_foo
and $form_bar
at least. Avoid doing that in the global scope - not because global is evil, but because nobody ever cleans up there.
但是,由于大多数情况下都是在本地化范围内进行的,因此,例如,如果您只需要所有字段用于输出,就可以应用htmlentities:
However, since mostly you do that in a localized scope, you can as well apply htmlentities if for example you need all fields just for output:
extract(array_map("htmlspecialchars", $_POST), EXTR_OVERWRITE, "form_");