Search code examples
phpbooleanphp-5.3filter-var

PHP filter_var: How to make sure the user provides correct data types - true or false only


I want to compare two arrays, one is set by default and another by user input.

When I have set a boolean value only in the default so I want to make sure the user won't use string or number. for instance, 'truex' or '1' is not acceptable.

Below is my sample of code,

$default = array(
    "randomise"     =>  false,
    "id"            =>  null
);

$config = array(
    "randomise"     =>  truex
);

function process_array($default,$config)
{
    # Loop the array.
    foreach($default as $key => $value)
    {

        if ((filter_var($default[$key], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === NULL) && (filter_var($config[$key], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === NULL)) 
        {
            return 'true or false only';
        }


    }

    # Return the result.
    return $array;
}

print_r(process_array($default,$config));

but this code returns 'true or false only' even though the user provides the correct data type. how can I fix this?


Solution

  • Alright first up you need to check that $config contains the key in $default. [Asside: If $config is user supplied... they could never user-supply an object like that, perhaps you meant $config=array("randomize"=>"truex");.. unless by user supplied you mean some other developer as the user (not a web user)).

    Second of all $config['id'] will always fail the test as you've written it (because it's not a boolean).

    So, I'm trying to guess at what you're doing here but I think this is what you want...

    $default = array("randomise"=>false,"id"=>null);
    //Example input
    $config = array("randomise"=>"truex");
    
    function process_array($default,$config) {
       foreach($default as $key => $value) {
          if (is_bool($default[$key])
              && isset($config[$key])) {
             //Update the array with the filtered value
             $config[$key]=filter_var($config[$key],FILTER_VALIDATE_BOOLEAN, 
                                      FILTER_NULL_ON_FAILURE);
             if ($config[$key]===null)
                return '$key can be true or false only';
             }
          }
       }
        return $array;
    }
    print_r(process_array($default,$config));