2

Hi I am quite new in PHP and I wanna know how can I check what type of variable the user entered

For example if the user entered a string return an error.Or if the user entered an integer redirect him to the next html page.

I think you got what I mean.Please help me :-)

  • 3
    Possible duplicate of [How to check the Datatype in php which is given in html textbox?](http://stackoverflow.com/questions/18267155/how-to-check-the-datatype-in-php-which-is-given-in-html-textbox) – eclarkso Aug 02 '16 at 13:21

4 Answers4

2

be aware:

var_dump(gettype('1')); // string

because

'1' !== 1
NDM
  • 6,731
  • 3
  • 39
  • 52
1

Try this

$type = gettype($input);

    if($type == 'integer'){
    // redirect

    }
    else{
        echo "error";

    }

The gettype() function is used to get the type of a variable. for more info read http://www.w3resource.com/php/function-reference/gettype.php

but i suggest use is_numeric() instead of gettype()

$type = is_numeric($input);

        if($type){
        // redirect

        }
        else{
            echo "error";

        }

because gettype treats variable in single quotes or double quotes as string so for gettype '1' is string not integer

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
0

Take a look at filter_var. It allows you to test your input as you're describing.

Example assuming that you want to validate it's an int value:

<?php

$input = 'some string';

if (filter_var($input, FILTER_VALIDATE_INT) === false) {
    // it's not an int value, return error
}
Dave Maple
  • 8,102
  • 4
  • 45
  • 64
0

Oh so ok i used the (is_numeric();)function and it worked thanks to all of you !! :DD