PHP:验证主键的 $_POST 数字字符串


PHP: Validating $_POST Numeric String for Primary Key

我正在使用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 数据验证整数的万无一失的方法是什么,或者您个人如何处理这个问题?

验证 PHP 中任何内容的万无一失的方法都是filter_var()filter_input()。当然,还可以使用PDO或MySQLi的预准备语句。

对于您的特定用例:

<?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;
}
?>

PHP 有过滤器输入

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

您可以与FILTER_VALIDATE_INT一起使用

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

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

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