- PHP input filtering for complex arrays
- $data = array(
- 'testarray' => array('2', '23', '10', '12')
- );
- $args = array(
- 'testarray' => array('filter' => FILTER_VALIDATE_INT,
- 'flags' => FILTER_FORCE_ARRAY
- )
- );
- $myinputs = filter_var_array($data, $args);
- $data = array(
- 'testhash' => array('level1'=>'email',
- 'level2'=> array('23', '10', '12'))
- );
- function validate_array($args) {
- return function ($data) use ($args) {
- return filter_input_array($data, $args);
- };
- }
- $args = array(
- 'user' => array(
- 'filter' => FILTER_CALLBACK,
- 'options' => validate_array(array(
- 'age' => array('filter' => FILTER_INPUT_INT),
- 'email' => array('filter' => FILTER_INPUT_EMAIL)
- ))
- )
- );
- $args = array(
- 'user/age' => array('filter' => FILTER_INPUT_INT),
- 'user/email' => array('filter' => FILTER_INPUT_EMAIL),
- 'user/parent/age' => array('filter' => FILTER_INPUT_INT),
- 'foo' => array('filter' => FILTER_INPUT_INT)
- );
- $data = array(
- 'user' => array(
- 'age' => 15,
- 'email' => 'foo@gmail.com',
- 'parent' => array(
- 'age' => 38
- )
- ),
- 'foo' => 5
- );
- function my_filter_array($data, $args) {
- $ref_map = array();
- foreach ($args as $key => $a) {
- $parts = explode('/', $key);
- $ref =& $data;
- foreach ($parts as $p) $ref =& $ref[$p];
- $ref_map[$key] =& $ref;
- }
- return filter_var_array($ref_map, $args);
- }
- var_dump(my_filter_array($data, $args));
- /** Like filter_var_array but recursive, this way you can nest your filters.
- * Small caveat : if an array in filters contains the keys 'filter' and
- * 'options' it will be considered as a filter rule.
- * param $data (mixed) : data to filter.
- * param $filters (mixed) : array of filters or filter.
- * return filtered data. Unknown fields will be deleted.
- * */
- function filter_var_recursive($data, $filters) {
- // Just a rule, don't recurse.
- if(!is_array($filters))
- return filter_var($data, $filters);
- // Only a detailed rule, don't recurse.
- if(array_key_exists('options', $filters) && array_key_exists('filter', $filters)) {
- // Hackish but ok.
- $ret = filter_var_array(array('value' => $data), array('value' => $filters));
- return $ret['value'];
- }
- // At this point the data should be an array, if it's not, we don't care.
- if(!is_array($data))
- $data = array();
- // Iterate and recurse.
- $ret = array();
- foreach($filters as $key => $filter) {
- if(!array_key_exists($key, $data))
- $ret[$key] = null;
- else
- $ret[$key] = filter_var_recursive($data[$key], $filter);
- }
- return $ret;
- }