Check if string can be logical php

I get a string from $ _GET and I want to check if it can be logical before using it for the mysql query part. Is there a better way to do this than:

function checkBool($string){
    $string = strtolower($string);
    if ($string == "true" || $string == "false" || 
        $string == "1" || $string == "0"){
        return true;
    }
    else {
        return false;
    }
}

if (checkBool($_GET['male'])){
    $result = mysql_query(
        "SELECT * FROM my_table " .
        "WHERE male='".$_GET['male']."'") or die(mysql_error());
}
+5
source share
6 answers

There is, by the way, a cleaner way to write it:

function checkBool($string){
    $string = strtolower($string);
    return (in_array($string, array("true", "false", "1", "0", "yes", "no"), true));
}

But yes. The only thing you recorded is the only way.

+8
source

You can use is_bool()or as suggested on php.net:

<?php
$myString = "On";
$b = filter_var($myString, FILTER_VALIDATE_BOOLEAN);
?>

http://php.net/manual/en/function.is-bool.php

The latter will accept strings such as "on" and "yes" as true.

+9
source

, , , , , , IN_ARRAY , .

+2

checkBool() , , SQL. TRUE FALSE, , :

TRUE FALSE 1 0 . .

, :

"SELECT * FROM my_table WHERE male='".$_GET['male']."'"

... :

'SELECT * FROM my_table WHERE male='.$_GET['male']

, checkBool() convertToBool(), , $_GET, .

, , BOOL. , :

TINYINT (1). .

, BOOL, ENUM, CHAR (1) - , 33 TRUE; -)

+1

FILTER_NULL_ON_FAILURE, filter_var() :

function CheckBool($Value) {
  return null !== filter_var($Value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}
+1

, "" "" , - :

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
}
0

All Articles