Test if string could be boolean PHP

后端 未结 8 2199
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-20 17:51

I\'m getting a string from a $_GET and I want to test if it could be a boolean, before I use it for a part of a mysql query. Is there a better way of doing it than:



        
8条回答
  •  不思量自难忘°
    2021-02-20 18:33

    For what it's worth, if you really wanted to accept "yes" or "no" as valid input from the user, then I'd do something like this:

    function toBoolean($string){
        $string = strtolower($string);
        if ($string == "true" || $string == "1"|| $string == "yes" )
            return true;
        elseif ($string == "false" || $string == "0" || $string == "no")
            return false;
        else
            throw new Exception("You did not submit a valid value, you naughty boy");
    }
    
    try {
        $query = "SELECT * FROM my_table WHERE male=" . (toBoolean($_GET['male']) ? "1" : "0" );
        $result = mysql_query($query) or die(mysql_error());
    } catch (Exception $e) {
        // handle bad user input here
    }
    

提交回复
热议问题