Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 775
legomolina Avatar asked May 30 '16 20:05

legomolina


People also ask

How disinfect JSON in PHP?

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. This could be worth a pull request at php's GitHub project page. May be needed often to just validate a json string.

What is JSON sanitizer?

The OWASP JSON Sanitizer Project is a simple to use Java library that can be attached at either end of a data-pipeline to help satisfy Postel's principle: be conservative in what you do, be liberal in what you accept from others.

What is sanitize in PHP?

Sanitizing data means removing any illegal character from the data. Sanitizing user input is one of the most common tasks in a web application. To make this task easier PHP provides native filter extension that you can use to sanitize the data such as e-mail addresses, URLs, IP addresses, etc.

Can PHP handle JSON?

PHP has some built-in functions to handle JSON.


1 Answers

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]);
}
like image 162
A Macdonald Avatar answered Sep 18 '22 01:09

A Macdonald