Filtering multiple variables in PHP



Most of the time, filtering and validation operations need to handle multiple variables. To avoid the need to call filter_input() or filter_var() repeatedly, both functions have counterparts capable of processing many variables in a single operation: filter_input_array() and filter_var_array().

The filter_input_array() function takes the following arguments:

$source: This indicates the superglobal array that contains the variables you want to filter. You must use one of the constants listed in Table 1, for example, INPUT_POST.

$instructions: This is an optional multidimensional array indicating how the variables are to be filtered. If this argument is omitted, the default filter is applied.


The filter_var_array() function takes the following arguments:

$data: This is an array containing the variables you want to filter or validate.

$instructions: This is the same as for filter_input_array().


The way you create the multidimensional array for the second argument is very similar to setting flags and options for filtering single variables. The top level of the array should contain an element for each of the variables to be processed. The value assigned to each variable should either be a filter constant or an array containing any combination of the following: ‘filter’, ‘options’, and ‘flags’.

The following listing shows examples of all variations:

$data = array('age' => 21,
'rating' => 4,
'price' => 9.95,
'thousands' => '100,000.95',
'european' => '100.000,95');

$instructions =
array('age' => FILTER_VALIDATE_INT,
'rating' => array('filter' => FILTER_VALIDATE_INT,
'options' => array('min_range' => 1,
'max_range' => 5)),
'price' => array('filter' => FILTER_SANITIZE_NUMBER_FLOAT,
'flags' => FILTER_FLAG_ALLOW_FRACTION),
'thousands' => array('filter' => FILTER_SANITIZE_NUMBER_FLOAT,
'flags' => FILTER_FLAG_ALLOW_FRACTION |
FILTER_FLAG_ALLOW_THOUSAND),
'european' => array('filter' => FILTER_VALIDATE_FLOAT,
'options' => array('decimal' => ','),
'flags' => FILTER_FLAG_ALLOW_THOUSAND)
);
$filtered = filter_var_array($data, $instructions);
var_dump($filtered);


To filter the same variables coming from the $_POST array, build the $instructions array in exactly the same way, and use filter_input_array() and the INPUT_POST constant, instead of filter_var_array() and $data, like this:

$filtered = filter_input_array(INPUT_POST, $instructions);

Even with an IDE that has PHP code hints and code completion, constructing this sort of multidimensional associative array is time consuming and prone to error.

Table 1: Superglobal constants used by filter functions
Code:

Constant 			Superglobal equivalent
INPUT_COOKIE 		      $_COOKIE variables
INPUT_ENV 			$_ENV variables
INPUT_GET 			$_GET variables
INPUT_POST 		      $_POST variables
INPUT_REQUEST 		    $_REQUEST variables
INPUT_SERVER 		     $_SERVER variables
INPUT_SESSION 		    $_SESSION variables