简体   繁体   中英

filter_var and validating integer values

I'm trying to validate if my variable is a 32-bit signed integer.

I thought I could use filter_var() and FILTER_VALIDATE_INT but apparently PHPs definition of an int is something entirely different, 999999999999999999 passes without problem.

Looking at the PHP docs it dosn't say anything specific. So what actually does filter_var($var, FILTER_VALIDATE_INT) validate?

You can set your own limits for FILTER_VALIDATE_INT :

$int = 999999999999999999;
$min = 1;
$max = 2147483647;

if (filter_var($int, FILTER_VALIDATE_INT, array("options"=>
    array("min_range"=>$min, "max_range"=>$max))) === false) {
    echo("Variable value is not within the legal range");
} else {
    echo("Variable value is within the legal range");
}
//This will output "Variable value is not within the legal range"

Source: http://www.w3schools.com/php/filter_validate_int.asp

Integer max size is based on the system:

on a 32-bit system : INT max will be 2147483647

on a 64-bit system : INT max will be 9223372036854775807

I think your problem lies more with integer :

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

FILTER_VALIDATE_INT allows for min_range and max_range to be passed as options. You should probably use those.

I was experiencing problems when using the limits for FILTER_VALIDATE_INT as well. After some trial and error of testing for the magic maximum number it came out to be 899795648511 on my machine. Here are my test results:
在此输入图像描述

Edit: The testing above was done by hard coding the test values into the PHP script as the max_range number. However, entering 899795648511 into the form field caused an error message to be generated that said "must be a whole number <= 2,147,483,647". So, this confirms dbruman's and Magicprog.fr's posts that the max limit is determined by 32-bit/64-bit platform.

You can use ctype_digit to check if it is an integer.

By default the maximum size for integer in PHP is in 0 - 2147483647 range.

It also depends in your platform, this works for 32bit platform.

Usually, this is the case.

if (ctype_digit(2147483647)) {
    echo 'integer';
}
if (!ctype_digit(2147483648)) {
    echo 'not an integer';
}
if (!ctype_digit(-2147483647)) {
    echo 'not an integer';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM