How can I limit the max value of number?

后端 未结 9 1932
小蘑菇
小蘑菇 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:32

    if (is_int($_GET['category']) and $_GET['category'] > 0 and $_GET['category'] <= 120)

    This will check if the number is greater than zero and smaller or equal to 120.

    0 讨论(0)
  • 2021-01-19 11:34

    I am adding this as some people might stumble here on the search for a way to this task based on the topic of your question.
    Sometimes you just want to "limit the max value of a numeric variable".

    $val=($val <= 120)?$val:120;
    

    That's the best way I found within one line (a combination of min() and max() can do the same but it's much more calculation intense) If the $val is larger than 120 it will be trimmed to 120, otherwise the original value is used.

    0 讨论(0)
  • 2021-01-19 11:35
    if (!ctype_digit($_GET['category']) || $_GET['category'] > 120) die('')
    

    Basically this says "If it's not a number or if it's larger than 120, stop"

    0 讨论(0)
提交回复
热议问题