Reputation: 43
I'm attempting to use filter_input_array() to validate some post data. Despite my best efforts the function seems to return null values inside of the $filter array(passing the condition) as opposed to failing the validation and returning false as I expect.
Here's an example of the code implementation:
$filters = array(
'phone' => FILTER_VALIDATE_INT,
'email' => FILTER_VALIDATE_EMAIL
);
if(filter_input_array(INPUT_POST, $filters)){
//filters are validated insert to database
} else{
//filters are invalid return to form
}
No matter kind of bad data (phone='a', email='{}/!~' for example) I enter the array is still returned instead of the function returning false and failing the condition. Any help would be greatly appreciated.
Upvotes: 4
Views: 1587
Reputation: 364
To keep the code the way you want it try this method
$filters = array(
'phone' => FILTER_VALIDATE_INT,
'email' => FILTER_VALIDATE_EMAIL
);
if(!in_array(null || false, filter_input_array(INPUT_POST, $filters)))
//enter into the db
else
//Validation failled
Upvotes: 2
Reputation: 1696
filter_input_array
function returns the result as an array of edited inputs, FALSE if it fails, NULL if each of inputs is not set. So you should get the result in a variable.
Another thing is to check falsehood first.
You need something like this
$filters = array(
'phone' => FILTER_VALIDATE_INT,
'email' => FILTER_VALIDATE_EMAIL
);
if(false === ($res = filter_input_array(INPUT_POST, $filters))){
/* Not valid */
} elseif(null == $res) {
/* Something is not set */
} else {
/* Everything is alright
* You can use $res variable here.
*/
}
Take a look at php manual : php.net manual
Upvotes: 2
Reputation: 22656
filter_input_array
wont return false if any filter fails. Rather it will return an array with the appropriate items set to false if they failed the filter (or null if they weren't set.
Upvotes: 3