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