6

Trying to pass a closure into filter_var_array(), but can't seem to make it work.

$clean = function( $html ) {
    return HTML::sanitize( $html, array('p','ul','ol','li'), array('class','style') );
};
$args = array( 'filter' => FILTER_CALLBACK, 'options' => $clean );

$fields = filter_var_array(
    array( $_POST['field1'], $_POST['field2'], $_POST['field3'] ),
    array( 'field1' => $args, 'field2' => $args, 'field3' => $args )
);

After the above is run, $fields is an empty array.

Note, individual filtering works fine:

$field1= filter_var( $_POST['field1'], FILTER_CALLBACK, array( 'options' => $clean ) );

Any ideas?

3
  • (sidenote) you can pass in $_POST directly instead of wrapping fields from it in a new array Commented Oct 4, 2012 at 16:48
  • 2
    @Gordon: Actually that is causing the problem. Commented Oct 4, 2012 at 16:50
  • I highly suggest you review the samples given in the manual: php.net/manual/en/function.filter-var-array.php - should make the usage more clear. Commented Oct 4, 2012 at 16:51

2 Answers 2

4

You are passing in the values of $_POST without their keys, hence no callbacks will be triggered. Just pass in the entire $_POST array instead, e.g.

$fields = filter_var_array(
    $_POST,
    array(
        'field1' => $args, 
        'field2' => $args, 
        'field3' => $args 
    )
);
Sign up to request clarification or add additional context in comments.

1 Comment

Ha, I knew I had to be making some bonehead error. Thanks everyone. I should of stepped away from the code for a couple of minutes before posting.
2

filter_var_array expects An array with string keys containing the data to filter and An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options.

Your implementation should be like this :

$clean = function ($html) {
    return HTML::sanitize($html, array('p','ul','ol','li'), array('class','style'));
};

$filter = array('filter' => FILTER_CALLBACK,'options' => $clean);
$args = array("field1" => $filter,"field2" => $filter,"field3" => $filter);
$fields = filter_var_array($_POST, $args);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.