开发者

is_int, is_numeric, is_float, and HTML form validation

A select field on my HTML form may yield 1 to 5 (integers). Using is_int rejects it every time, because the $_POST['rating'] is viewed as a string.

After co开发者_运维知识库nsulting the PHP Manual, it seems is_numeric() && !is_float() is the proper way to validate for an integer in this case.

But I want to be certain, so please confirm or fire away at my logic.


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 non-integer or out-of-range, or the valid value itself (as an integer.)


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

Another way to guarantee something is an integer is to cast it...

$id = (int) $id;


You could use the following regular expression:

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

I does validate digits with leading zeros though...


if you want to know if $_POST['rating'] is an int before you even try to cast do use is_numeric() && !is_float() as you have. This will tell you if the string is an int or not. If you just cast to an int and there is a non numeric all the numbers before the first letter in the string is turned into an int.

x = 457h
print (int)x

outputs 457

x = h56
print (int)x

outputs 0


is_int requires the input content is a integer. is_numeric requires the input content is a integer or a string including just 0-9.

but I am wondering the result if I put a number that is bigger than PHP_INT_MAX as the parameter into the above 2 functions.


You can always cast it as an int.

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

This will remove the need to validate it (even though you should always validate form data). It may reduce your steps is what I'm getting at.


If you're testing for digits only (what an integer usually is ;)), I tend to use ctype_digit instead of is_int. That way, you won't lose data through casting, and you can just use a string:

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

That'll output "yep".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜