Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit the max value of number?

Tags:

php

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 can not be passed any negative number. How can I limit the max value in the simplest way?

if (!ctype_digit($_GET['category'] AND ...) die('');

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

I was thinkig about intval but it can pass negative numbers.

like image 742
Lucas Avatar asked Dec 21 '22 01:12

Lucas


2 Answers

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.
like image 71
Linus Kleen Avatar answered Dec 24 '22 03:12

Linus Kleen


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"

like image 28
Tom van der Woerdt Avatar answered Dec 24 '22 01:12

Tom van der Woerdt