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
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.
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.
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.
PHP has some built-in functions to handle JSON.
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With