I want to use filters on complex data structures such as JSON request bodies (used in for example Angular.js)
I wrote a unified function much like this:
<?php
function validate($input, $varname, $filters, $default) {
$names = explode('.', $varname);
$ptr = $input;
foreach($names as $name) {
if (is_array($ptr)) {
if (ctype_digit($name)) {
$index = intval($name);
} else {
$index = $name;
}
if (isset($ptr[$index])) {
$ptr = $ptr[$index];
} else {
return $default;
}
} elseif (is_object($ptr)) {
if (isset($ptr->$name)) {
$ptr = $ptr->$name;
} else {
return $default;
}
}
}
// filters
$phfilter = new \Phalcon\Filter();
foreach($filters as $filter) {
$ptr = $phfilter->sanitize($ptr, $filter);
if (!$ptr) {
return $default;
}
}
return $ptr;
}
I have two questions:
-
There is a mention in the documentation that you can also pass multiple filternames to sanitize(). How do I do that and in which order are these filters applied?
- Is there a better way to do this then writing my own function?
As a remark: since most software vulnerabilities are a consequence of poorly filtered input data it would be most useful to have a simple sanitizing validation mechanism that checks for both existence and format of the input variables, stripping of all inappropriate tags and characters, and dismissing unexpected input alltogether. As this is a very common task it would be even more convenient to compress the code to a single function call such as I triy to do above.