用php清理JSON [英] Sanitize JSON with php

查看:106
本文介绍了用php清理JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是使用filter_var($ var,FILTER,FLAG);当我从$ _GET,$ _ POST等获取数据时,但是现在此数据是JSON字符串,但是我没有找到任何过滤器来净化JSON.有人知道如何实现此过滤器吗?

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/zh-CN /function.filter-var.php

PHP filter_var(): http://php.net/manual/en/function.filter-var.php

PHP FILTER CONST: http://php.net/manual/zh/filter.filters.sanitize.php

PHP FILTER CONST: http://php.net/manual/en/filter.filters.sanitize.php

推荐答案

首先将JSON解析为PHP数组,然后像处理常规请求内容一样对数组中的每个值进行过滤,您可以将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]);
}

这篇关于用php清理JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆