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
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.
if(!ctype_digit($_GET['category']) || $_GET['category'] > 120) {
...
if(!ctype_digit($_GET['category']) || $_GET['category'] > 120) //do whatever you want
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.
// 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...
}
Here's a simple way:
function set_range($value, $minimum, $maximum) {
return min(max($minimum, $value), $maximum);
}
Here's what we're doing:
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