Home » Php » isinteger – PHP is_int is not performing as expected

isinteger – PHP is_int is not performing as expected

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a page (index.php) that takes a GET variable from the URL and checks it for security purposes. This GET variable should only be an integer. I am using the following code to check this, but in all instances, integer or not, I get the index.php page. The header never appears. After this code, the rest of the page appears starting with the html tag.

PHP:

<?php ob_start(); session_start();
$q=trim($_GET['q']);
if (!is_numeric($q)){
header("HTTP/1.0 404 Not Found");
}
?>
How to&Answers:

It won’t be an integer if it’s passed in a query string.

Try is_numeric()

Answer:

There is a better way to do this, which is casting to int:

$q = (int) $_GET['q'];

The is_int is behaving as expected. Because GET arguments are always strings. Try var_dumping them.

Answer:

Sometimes you want to validate input which should be number but in $_GET or $_POST you will get it as string. is_numeric() may be problematic, because it allows hex, binary and octal format (from manual):

Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but only without sign, decimal and exponential part.

You can’t use is_int() as it’s only for integer values (not string!) so… You can validate numbers which are string AND integer that way:

function is_int_val($value){

    if( ! preg_match( '/^-?[0-9]+$/', $value ) ){
        return FALSE;
    }


    /* Disallow leading 0 */

    // cast value to string, to make index work
    $value = (string) $value;

    if( ( $value[0] === '-' && $value[1] == 0 ) || ( $value[0] == 0 && strlen( $value ) > 1 ) ){
        return FALSE;
    }


    return TRUE;
}

is_int_val('33');  // true
is_int_val('33a'); // false
is_int_val('033'); // false

It is also possible to override is_int() function, using override_function() but it still may be useful in original version.