0

我使用 is_numeric 来验证来自 POST 数据的整数,例如:

if( ! is_numeric($_POST['integer_string'])) return FALSE // not a integer

然后我发现如果值有小数,is_numeric 将返回 TRUE。

接下来我尝试了强制转换和 is_int:

$int = (int) $_POST['numeric_string'];
if( ! $int)  return FALSE // not a integer

但是在传递一个非数值后,强制转换会截断整数。

$int = '222i2';
echo $int;
// 222

我试图验证的整数将在 SQL 的 WHERE 子句中使用,以识别整数主键。

从 POST 数据中验证整数的万无一失的方法是什么,或者您个人如何处理这个问题?

4

3 回答 3

2

PHP 有过滤器输入

http://www.php.net/manual/en/function.filter-input.php

您可以与 FILTER_VALIDATE_INT 一起使用

于 2013-11-04T16:28:18.640 回答
2

验证 PHP 中任何内容的万无一失的方法是filter_var()filter_input(). 加上当然使用PDOMySQLi的准备好的语句。

对于您的特定用例:

<?php

$id = filter_input(
    INPUT_POST,            // Submitted via $_POST
    "integer_string",      // Offset name in $_POST
    FILTER_VALIDATE_INT,   // The validation method
    FILTER_REQUIRE_SCALAR  // NULL and empty aren't valid
);

if ($id === false) {
    throw new InvalidArgumentException("Not an int!");
}

// Assuming you have a Database object that wraps your DB stuff.
$database->query("SELECT * FROM `table` WHERE `id` = ? LIMIT 1", "d", [ $id ]);

?>

如果您的 PHP 版本不支持各种过滤器功能,请执行以下操作:

<?php

if (ctype_digit($_POST["integer_string"]) === false) {
    throw new InvalidArgumentException;
}

// Before PHP 5.1.0
if (empty($_POST["integer_string"]) || ctype_digit($_POST["integer_string"]) === false) {
    throw new InvalidArgumentException;
}

?>
于 2013-11-04T16:30:15.693 回答
0

对于 php < 5.2,您可以使用正则表达式:

preg_match("/^[0-9]+$/", $_POST["integer_string"]);

http://php.net/manual/en/function.preg-match.php

于 2013-11-04T16:30:59.667 回答