Search code examples
phpjsonfilter-var

Sanitize JSON with php


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


Solution

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