php – Problem checking the type of INT variables


I have a problem that I can't understand, I'm passing two variáveis to the produtos page, the values ​​are int , on this page I'm receiving the variables and testing if they are really int and sanitizando them, but the test always falls on the exception "Incorrect Value".

What I have is this:

if (is_numeric($_GET['dep'])) {  
$dep = Sanitize::filter($_GET['dep']); 
} else {  
    die ("Valor Incorreto") ;  

if (is_numeric($_GET['sub'])) {  
$sub  = Sanitize::filter($_GET['sub']); 
} else {  
    die ("Valor Incorreto") ;  

I may be missing something very simple, but honestly I couldn't see it.


Sanitization usually comes before validation. What set up does the opposite. It tries to validate and sanitize later, but as it may not be receiving the appropriate type, it always ends up in the error message.

One way to sanitize is to cast the type using intval() or preceding (int) .

$var = (int)$var;


$var = intval($var);

However, beware of using type casting for what you are doing as in recent versions of PHP it may not work as expected. It is safer to do character substitution using string manipulation functions to perform consistent sanitization. And remembering that the cast itself is already a sanitization for the case in question.

Example (PHP5.6.19):

// http://localhost/tmp.php?n=a
echo (int)$_GET['n'];

This test above returns an integer ZERO. It is an unexpected result as the received value does not contain any numbers.

A more consistent way is by replacing non-numeric characters:

function numbers_only($str, $exception = '')
    return preg_replace('#[^0-9'.$exception.']#', '', mb_convert_kana($str, 'n'));

// http://localhost/tmp.php?n=a
echo '<br>numbers_only(): '.numbers_only($_GET['n']);

In this example, since there are no numbers, it returns empty because sanitization removed everything that was not recognized as a numeric character.

Note that it also auto-converts zenkaku characters, allowing zenkaku numbers to be sanitized to standard ASCII with the mb_convert_kana() function.

Adapting to your case, it would look like this

// Checking if parameter exists
$n = isset($_GET['dep'])? $_GET['dep']: null;

// Checking if the parameter is not empty or equals to ZERO
if (!empty($n) || $n == '0') {
    // Sanitization
    $n = numbers_only($n);

    // Check again if not empty and different of ZERO
    if (empty($n) && $n != '0') {
        $err = 'parameter do not contains numbers';
} else {
    $err = 'parameter cannot be empty';

if (empty($err)) {
    echo 'number: '.$n;
} else {
    echo 'error: '.$err;

In the example above, the value 0 (ZERO) is accepted. If you want to remove the zero, remove it from the conditionals || $n == '0') and && $n != '0' .

Scroll to Top