How can I limit the max value of number?

后端 未结 9 1931
小蘑菇
小蘑菇 2021-01-19 11:09

I want to secure my page by checking if the value is digital (0,1,2,3) and if it is in the range from 0 to 120. I think ctype_digit function limits numbers, so

相关标签:
9条回答
  • 2021-01-19 11:11

    You might want to take a look at PHP's Data Filtering.

    It provides a filter for your task (FILTER_VALIDATE_INT) which also accepts min_range and max_range parameters:

    $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.
    
    0 讨论(0)
  • 2021-01-19 11:12
    if(!ctype_digit($_GET['category']) || $_GET['category'] > 120) {
    ...
    
    0 讨论(0)
  • 2021-01-19 11:12
    if(!ctype_digit($_GET['category']) || $_GET['category'] > 120) //do whatever you want
    
    0 讨论(0)
  • 2021-01-19 11:15

    Not an answer, but here's why what you had wouldn't work:

    if (!ctype_digit($_GET['category'] > 120) ?
                     ^^^^^^^^^^^^^^^^^^^^^^^
    

    The indicated part is inside the ctype call. So first PHP will check if the GET value is greater than 120, turning that into a boolean true/false. THEN the ctype is applied, which will always be false, as a boolean value is not a digit.

    0 讨论(0)
  • 2021-01-19 11:20
    // 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...
    }
    
    0 讨论(0)
  • 2021-01-19 11:25

    Here's a simple way:

    function set_range($value, $minimum, $maximum) {
        return min(max($minimum, $value), $maximum);
    }
    

    Here's what we're doing:

    1. compare the number with our minimum value, and take the highest number.
    2. compare that result with our maximum value, and take the lowest number.

    And here's a test:

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

    If you want to check if a number is within a range, you could do this:

    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
    
    0 讨论(0)
提交回复
热议问题