【问题标题】:filter input and isset过滤输入和 isset
【发布时间】:2014-05-25 21:47:28
【问题描述】:

我需要同时过滤$_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(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');

}

【问题讨论】:

  • 既然它只是帮助你删除非法字符,我认为没有理由不这样做。

标签: php input sanitization


【解决方案1】:

当 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 清理库来帮助您。

【讨论】:

    【解决方案2】:

    由于您只检查值,因此在您提供的示例代码中并非绝对必要。
    然而,总是清理你的输入总是一个好习惯,因为你可能会用它做一些事情。如果您想了解为什么不清理输入就使用输入不是一个好主意,请查看XSS exploit

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2014-06-15
      • 2014-01-17
      • 2012-02-07
      相关资源
      最近更新 更多