我总是使用filter_var($ var,FILTER,FLAG);当我从$ _GET,$ _POST等获取数据时,但现在这个数据是一个JSON字符串,但我没有找到任何过滤器来清理JSON。有谁知道如何实现这个过滤器?
PHP filter_var():http://php.net/manual/en/function.filter-var.php
PHP FILTER CONST:http://php.net/manual/en/filter.filters.sanitize.php
答案 0 :(得分:6)
首先将JSON解析为PHP数组,然后像处理常规请求内容一样过滤数组中的每个值,您可以将JSON键映射到原理图过滤器和标记/选项,例如。
$filters = array(
'email'=>FILTER_VALIDATE_EMAIL,
'url'=>FILTER_VALIDATE_URL,
'name'=>FILTER_SANITIZE_STRING,
'address'=>FILTER_SANITIZE_STRING
);
$options = array(
'email'=>array(
'flags'=>FILTER_NULL_ON_FAILURE
),
'url'=>array(
'flags'=>FILTER_NULL_ON_FAILURE
),
//... and so on
);
$inputs = json_decode($your_json_data);
$filtered = array();
foreach($inputs as $key=>$value) {
$filtered[$key] = filter_var($value, $filters[$key], $options[$key]);
}
答案 1 :(得分:3)
为此您使用filter_var_array:
$inputs = filter_var_array( json_decode( $your_json_data, true ), [
'email' => [ 'filter' => FILTER_VALIDATE_EMAIL,
'flags' => FILTER_NULL_ON_FAILURE ],
'url' => [ 'filter' => FILTER_VALIDATE_URL,
'flags' => FILTER_NULL_ON_FAILURE ],
'name' => FILTER_VALIDATE_NAME,
'address' => FILTER_SANITIZE_STRING
] );