在mysql插入之前清理数组值 [英] Sanitizing array values before mysql inserts

查看:59
本文介绍了在mysql插入之前清理数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP表单处理程序中具有以下代码块:

I have the following code blocks in a PHP form-handler:

function filter($data) {
    $data = trim(htmlentities(strip_tags($data)));

    if (get_magic_quotes_gpc()) {
        $data = stripslashes($data);
    }
    $data = mysql_real_escape_string($data);

    return $data;
}

foreach($_POST as $key => $value) {
    $data[$key] = filter($value);
}

我正在修改表单,使其现在包括复选框组:

I am modifying my form to now include checkbox groups:

例如:

<input type="checkbox" name="phone_prefs[]" value="prefer_home">
<input type="checkbox" name="phone_prefs[]" value="prefer_cell">
<input type="checkbox" name="phone_prefs[]" value="prefer_work">
etc.

由于此代码,我现在在_POST变量中包含数组,而不仅仅是字符串.

Because of this code I now have arrays in my _POST variables rather than just strings.

我是否正确地认为我的filter()函数实际上无法正确清理数组?我需要对我的filter()函数进行哪些更改,以确保完全清除复选框的数组,而不是将其作为SQL注入攻击的简单目标?

Am I correct in thinking that my filter() function the will not actually sanitize arrays properly? What changes do I need to make to my filter() function to make sure the arrays for the checkboxes are sanitized completely and not an easy target for SQL injection attacks?

推荐答案

您的函数相当不错,但是如果递归地进行,它将为您抓取嵌套的数组

Your function is pretty good, but if you make it recursive it'll crawl nested arrays for you

function filter(&$array) {
    $clean = array();
    foreach($array as $key => &$value ) {
        if( is_array($value) ) {
            filter($value);
        } else {
            $value = trim(strip_tags($value));
            if (get_magic_quotes_gpc()) {
                $data = stripslashes($value);
            }
            $data = mysql_real_escape_string($value);
        }
    }
}

filter($_POST); # filters $_POST and any nested arrays by reference

忽略htmlentities().如果需要,请在输出值时使用它-而不是在将其用作输入时使用.

Leave out htmlentities(). If you need it, then use it when outputting the values - not when getting them as input.

这篇关于在mysql插入之前清理数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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