PHP filter

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.


为了让代码保持您想要的样子,请尝试使用此方法

      $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

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.


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

链接地址: http://www.djcxy.com/p/92700.html

上一篇: var对URL不正确

下一篇: PHP过滤器