在哪里清理 PHP $_POST[] 输入? [英] Where to sanitize PHP $_POST[] input?
问题描述
我正在使用 codeigniter 框架.
I am using codeigniter framework.
我应该在哪里清理 PHP 输入 - 控制器或模型?
where should i sanitize PHP input - controller or model ?
推荐答案
我曾经是尽可能集中卫生的朋友,但对 SO 进行了广泛的讨论(例如这里)改变了我的想法.绝对值得一读.
I used to be a friend of centralizing sanitation as much as possible, but extensive discussion on SO (for example here) has changed my mind. Definitely worth a read.
我向您提交以下实践:
在中央验证例程中,不要进行清理,或者只是粗略"检查(例如,数据类型)和大小($_POST[category_name"] 不应大于 200 字节.")
In a central validation routine, do no sanitation, or just "rough" checks (say, for data type) and size ("$_POST["category_name"] should not be larger than 200 bytes.")
将传入变量标记为不安全(例如 $unsafe_id = $_POST["category_name"];
).将它们存储在任何可用的控制器/类/构造中.
Mark incoming variables as unsafe (e.g. $unsafe_id = $_POST["category_name"];
). Store them in whatever controller / class / construct you have available for it.
清理数据使用它的地方.例如,如果在 exec
调用中使用传入数据,请直接在调用前进行必要的清理:
Sanitize data where it is used. If incoming data is used in a exec
call for example, do the necessary sanitation directly in front of the call:
$safe_category_name = escapeshellargs($unsafe_category_name);
exec("external_binary -category_name '$safe_category_name'");
如果相同的数据被用在一个,比如说,mySQL 查询中,在调用前再次清理它:
if the same data is then used in a, say, mySQL query, again sanitize it in front of the call:
$safe_category_name = mysql_real_escape_string ($unsafe_category_name);
mysql_query("SELECT * FROM items WHERE category_name = '$safe_category_name'");
(这只是一个例子.如果从头开始一个项目,你会想要使用 PDO 和准备好的语句,这样可以避免在这种情况下转义传入的数据.)
(this is just an example. If starting a project from scratch, you will want to use PDO and prepared statements, which takes away the hassle of escaping incoming data in this context.)
如果在网页中输出相同的数据,再次在调用前直接进行卫生:
if the same data is then output in a web page, again do the sanitation directly in front of the call:
$safe_category_name = htmlspecialchars($unsafe_category_name);
echo "<span>$safe_category_name</span>";
这种做法
建立一个工作流程,假设存在需要首先处理的不安全变量,这会导致更安全的编程风格 IMO.
Establishes a workflow that assumes there are unsafe variables that need to be dealt with first, which leads to a safer programming style IMO.
防止不必要的转换.
帮助消除存在一种使输入安全"的一键式方法的错觉.没有.卫生情况 100% 取决于环境.
Helps fight the illusion that there is a one-click method to make input "safe." There isn't. Sanitation depends 100% on context.
这篇关于在哪里清理 PHP $_POST[] 输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!