Is_int, is_numeric, is_float and HTML form validation

The select box in my HTML form can give from 1 to 5 (integers). Using is_int rejects it every time because $_POST['rating'] treated as a string.

After consulting the PHP manual, it seems that is_numeric() && !is_float() is the correct way to check for an integer in this case.

But I want to be sure, so please confirm or remove my logic.

+4
source share
7 answers

I would use is_numeric() because user input always comes as a string (as far as I know).

Another way to guarantee something is an integer - this is it ...

 $id = (int) $id; 
+4
source

I would probably use something like this:

 $value = filter_var( $_POST['rating'], FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 5))); 

filter_var() will return either boolean false if the value is not integer or out of range, or a real value (as an integer).

+4
source

You can always use it as an int.

 $rating = (int)$_POST['rating']; 

This will eliminate the need to validate it (although you should always check the form data). It can reduce your steps - this is what I get.

0
source

if you want to know that $_POST['rating'] is an int, before you even try to throw, use is_numeric() && & !is_float() , as you have. This will tell you whether the string is int or not. If you just pass int and there is a numeric number of all numbers before the first letter in the string is converted to int.

 x = 457h print (int)x 

outputs 457

 x = h56 print (int)x 

outputs 0

0
source

If you are testing only numbers (which is usually an integer;)), I prefer to use ctype_digit instead of is_int. This way you won’t lose data with casting, and you can just use the line:

 <?php $_POST['foo'] = '42'; echo ctype_digit( (string) $_POST['foo'] ) ? 'yep' : 'nope'; 

This will print "yep".

0
source

You can use the following regular expression:

 preg_match('/^[0-9]{1,}$/', $value); 

I check digits with leading zeros though ...

0
source

is_int requires the input content to be an integer. is_numeric requires the input content to be an integer or string, including only 0-9 .

but I'm interested in the result if I put a number greater than PHP_INT_MAX as a parameter in the above 2 functions.

-1
source

Source: https://habr.com/ru/post/1345886/


All Articles