[英]How can I limit the max value of number?
我想通过检查值是否为数字 (0,1,2,3) 以及它是否在 0 到 120 的范围内来保护我的页面。我认为ctype_digit
函数限制了数字,因此不能传递任何负数。 如何以最简单的方式限制最大值?
if (!ctype_digit($_GET['category'] AND ...) die('');
if (!ctype_digit($_GET['category'] > 120) ?
我在考虑intval
但它可以传递负数。
您可能想看看PHP 的数据过滤。
它为您的任务( FILTER_VALIDATE_INT
)提供了一个过滤器,它也接受min_range
和max_range
参数:
$value = filter_var($_GET['category'], FILTER_VALIDATE_INT, array(
'options' => array(
// An optional default value
'default' => 123,
// Desired validation range
'min_range' => 0,
'max_range' => 120
),
));
// $value is FALSE when validation failed, or an "int" with
// the correct value.
if (!ctype_digit($_GET['category']) || $_GET['category'] > 120) die('')
基本上这是说“如果它不是数字或大于 120,则停止”
我添加此内容是因为有些人可能会根据您的问题主题在这里寻找完成此任务的方法。
有时您只想“限制数字变量的最大值”。
$val=($val <= 120)?$val:120;
这是我在一行中找到的最好方法(min() 和 max() 的组合可以做同样的事情,但计算量更大)如果 $val 大于 120,它将被修剪为 120,否则为原始值用来。
这是一个简单的方法:
function set_range($value, $minimum, $maximum) {
return min(max($minimum, $value), $maximum);
}
这是我们正在做的事情:
这是一个测试:
// Check every fifth number between 0-60 and
// set output to within range of 20 to 40.
//
for ($i = 0; $i < 60; $i += 5) {
echo $i . " becomes " . set_range($i, 20, 40) . PHP_EOL;
}
如果你想检查一个数字是否在一个范围内,你可以这样做:
function in_range($value, $minimum, $maximum) {
return ($value >= $minimum) && ($value <= $maximum);
}
echo (in_range( 7, 20, 40)) ? "yes" : "no"; // output: no
echo (in_range(33, 20, 40)) ? "yes" : "no"; // output: yes
if (is_int($_GET['category']) and $_GET['category'] > 0 and $_GET['category'] <= 120)
这将检查数字是否大于零且小于或等于 120。
if(!ctype_digit($_GET['category']) || $_GET['category'] > 120) //do whatever you want
if(!ctype_digit($_GET['category']) || $_GET['category'] > 120) {
...
// Make sure it is an integer.
$category = (int) $_GET['category'];
if($category<0 OR $category>120){
// Code to be executed if the number is out of range...
}
不是答案,但这就是您所拥有的不起作用的原因:
if (!ctype_digit($_GET['category'] > 120) ?
^^^^^^^^^^^^^^^^^^^^^^^
指示的部分在 ctype 调用中。 所以首先 PHP 将检查 GET 值是否大于 120,将其转换为布尔值 true/false。 然后应用 ctype,这将始终为 false,因为布尔值不是数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.