我是否需要同时过滤$_GET['action']
和$_GET['id']
??
正常
if (isset($_GET['action']) && $_GET['action'] == 'delete') {
/* Do Something*/
}
过滤
if (isset($_GET['action']) && filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING) == 'delete') {
/* Do Something*/
}
正常
if (isset($_GET['id']) && !empty($_GET['id'])) {
/* Do Something*/
}
过滤
if (isset($_GET['id']) && !empty(filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT))) {
/* Do Something*/
}
已编辑我是否需要过滤(filter_input)$ id或PDO :: PARAM_INT做同样的事情?
if (isset($_GET['id']) && !empty($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$query = "SELECT * FROM table WHERE id = :id";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
print htmlspecialchars($row['test'], ENT_QUOTES, 'UTF-8');
}
答案 0 :(得分:2)
当GET变量以?foo=
给出时,过滤器的返回值为空字符串''
。
当过滤undefined
变量时,过滤器的返回值为NULL
。
当预期使用整数时,使用类型转换将新变量分配给私有范围,您可以通过以下方式验证ID:
$id = intval(filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT));
try {
if(isValidID($id)) {
echo $id . ' is OK!';
}
// ...
} catch(Exception $e) {
echo $e->getMessage();
}
function isValidID($id)
{
if($id == 0 /* you can put more business logic in this test */) {
throw new InvalidArgumentException('Invalid value for ID');
}
return true;
}
字符串就像名字一样,可以通过以下方式验证:
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_STRING);
try {
if(isValidName($name)) {
echo $name . ' is OK!';
}
// ...
} catch(Exception $e) {
echo $e->getMessage();
}
function isValidName($name)
{
if(!$name or strlen($name) < 3 or is_numeric($name) /* you can put more business logic in this test */) {
throw new InvalidArgumentException('Invalid value for a customer name');
}
return true;
}
在使用PDO时,始终过滤输入值。写下你的,或找一个PHP消毒库来帮助你。
答案 1 :(得分:1)
由于您只检查了值,因此在您提供的示例代码中并不是必需的 但是,始终对您的输入进行消毒始终是一个好习惯,因为您可能会对它做些什么。检查XSS exploit是否需要一些示例,说明为什么在不清理它们的情况下使用输入不是一个好主意。