Sanitize JSON with php

↘锁芯ラ 提交于 2020-01-10 02:50:45

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/37533162/sanitize-json-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!