PHP如何以正确的方式过滤所有$ _POST变量 [英] PHP How to filter 'in a correct way' All $_POST variables

查看:606
本文介绍了PHP如何以正确的方式过滤所有$ _POST变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Netbeans,每当我尝试访问$ _POST或$ _GET中的变量时,建议使用诸如filter_input(INPUT_POST,'id')之类的东西作为安全性"(我不认为它比使用filter_input更安全默认的NON过滤器,但无论如何..).

Using Netbeans, whenever i try to access a variable in $_POST or $_GET, i'm adviced to use something like: filter_input(INPUT_POST,'id'), for 'safety' (i don't think it's any safer than using filter_input with the default NON filter, but anyways..).

这让我思考了这篇文章的答案:如何在帖子(PHP)中获取所有变量

This got me thinking about the answer to this post: How to grab all variables in a post (PHP)

您有:

foreach ($_POST as $key => $value) {
    //do something
    echo $key . ' has the value of ' . $value;
}

filter_input()仅适用于$ _POST内部的单个变量

filter_input() only works for individual variables inside $_POST

我的问题是,如何通过过滤重写"$_POST as $key"以适合NetBeans告诉我的假定访问标准?

My question is, How can i re-write "$_POST as $key" with filtering to fit this supposed access standard that NetBeans is telling me about?.

推荐答案

您可以使用$_POST. php"rel =" noreferrer> filter_input_array

You can filter whole $_POST using filter_input_array

$safePost = filter_input_array(INPUT_POST);

使用第二个参数可以更改过滤器

Using second parameter you can change filter

$safePost = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

您还可以定义按属性过滤器

You can also define per-property filters

$safePost = filter_input_array(INPUT_POST, [
    "id" => FILTER_VALIDATE_INT,
    "name" => FILTER_SANITIZE_STRING,
    "email" => FILTER_SANITIZE_EMAIL
]);


如果我对输入一无所知怎么办?

What if I know nothing about input?

嗯,您总是知道一些事情,知道您期望得到什么. 如果用户提供了无效的输入,您应该对此做出反应.

Well, you always know something, you know what you expect to get. And if user provides invalid input you should react to that.

如果您期望字段id中存在整数,并且用户向您发送了tomato,那么您应该返回错误并通知用户,他发送的请求出了什么问题.

If you expect integer in field id and user sends you tomato, then you should reply with error informing user what is wrong with request he sent.

这篇关于PHP如何以正确的方式过滤所有$ _POST变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆