Sanitize JSON with php

2020-02-10 05:20发布

问题:

I always use filter_var($var, FILTER, FLAG); when I get data from $_GET, $_POST and so on, but now this data is a JSON string but I didn't find any filter to sanitize JSON. Anyone know how to implement this filter?

PHP filter_var(): http://php.net/manual/en/function.filter-var.php

PHP FILTER CONST: http://php.net/manual/en/filter.filters.sanitize.php

回答1:

Parse the JSON first into a PHP array and then filter each value in the array as you do with regular request content, you could map the JSON keys to schematic filters and flags/options e.g.

$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]);
}


回答2:

You use filter_var_array for this:

$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
] );