16

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

legomolina
  • 1,043
  • 2
  • 13
  • 33
  • how you get json?? – Mahdi Majidzadeh May 30 '16 at 20:23
  • 2
    [json_decode](http://php.net/manual/en/function.json-decode.php) return null if the json string is invalid. Then you should filter var the containing properties depending on what they are (number, email, etc) – JimL May 30 '16 at 20:27

2 Answers2

15

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]);
}
A Macdonald
  • 814
  • 1
  • 7
  • 10
  • 1
    This could be worth a pull request at php's GitHub project page. May be needed often to just validate a json string. I usually use for this purpose instead of `filter_var` `filter_input`. But in your meaning it's the same. Both functions should have a `FILTER_VALIDATE_JSON` constant. – alpham8 Jun 20 '18 at 13:37
11

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

EDIT: since PHP8 FILTER_SANITIZE_STRING is deprecated, you need to use htmlspecialchars now to sanitize strings.

patrick
  • 11,519
  • 8
  • 71
  • 80
  • 2
    What if one of json vars in the sent json was array, e.g. {"items": [2,5,15...]} - what FILTER_... use to get that array "items"? – forsberg Mar 13 '20 at 16:35
  • 1
    @forsberg If the json has a array as a value, you run a filter on that as well with a loop. It's the same process... you have to keep breaking it down into smaller and smaller pieces. – RockyK Mar 06 '21 at 22:16