Sanitize JSON with php
Asked Answered
D

2

17

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

Deontology answered 30/5, 2016 at 20:21 Comment(2)
how you get json??Honk
json_decode return null if the json string is invalid. Then you should filter var the containing properties depending on what they are (number, email, etc)Discoloration
B
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]);
}
Bryna answered 30/5, 2016 at 20:47 Comment(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.Sharlenesharline
S
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.

Simitar answered 24/8, 2018 at 12:30 Comment(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"?Humane
@Humane 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.Downwind

© 2022 - 2024 — McMap. All rights reserved.