检查用户输入的类型(PHP)


Check type of user input (PHP)

嗨,我是PHP的新手,我想知道如何检查用户输入的变量类型

例如,如果用户输入了一个字符串,则返回一个错误。或者,如果用户输入了一个整数,则将其重定向到下一个html页面。

我想你明白我的意思了。请帮我:-)

  • gettype
  • is_numeric

注意:

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

因为

'1' !== 1

试试这个

$type = gettype($input);
    if($type == 'integer'){
    // redirect
    }
    else{
        echo "error";
    }

gettype() function用于获取variable的类型。欲了解更多信息,请阅读http://www.w3resource.com/php/function-reference/gettype.php

我建议使用is_numeric()而不是gettype()

$type = is_numeric($input);
        if($type){
        // redirect
        }
        else{
            echo "error";
        }

因为gettypesingle quotesdouble quotes中的variable视为字符串,所以对于gettype'1'string而不是integer

看看filter_var。它允许您在描述时测试您的输入。

假设您想验证它是一个int值的示例:

<?php
$input = 'some string';
if (filter_var($input, FILTER_VALIDATE_INT) === false) {
    // it's not an int value, return error
}

哦,好吧,我用了(is_numeric();)感谢大家!!:DD