消毒& desanitize多维数组

时间:2015-05-26 10:31:42

标签: php arrays multidimensional-array

我写了以下课程:

class Sanitizer {

    public function sanitizeSingle ($string) {  
        if (get_magic_quotes_gpc()) {
            $string = stripslashes($string);
        }

        return trim(htmlspecialchars($string, ENT_QUOTES)); 
    }

    public function sanitize ($string) {
        if (is_array($string)) {
            foreach ($string as $k => $v) {
                $string[$k] = $this->sanitizeSingle($v);
            }
        }
        else {
            $string = $this->sanitizeSingle($string);
        }

        return $string;
    }

    public function desanitize ($string) {
        return trim(htmlspecialchars_decode($string, ENT_QUOTES));
    }

}

问题在于,虽然它适用于字符串和一维数组,但我在多维数组中遇到以下错误:

  

警告:htmlspecialchars()要求参数1为字符串,数组   在第10行的C:\ wamp \ www \ classes \ Sanitizer.php中给出

我该如何解决这个问题?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您的代码未在$v中评估数组 像这样修改你的foreach块,这个修改将清理任何级别的嵌套数组

 foreach ($string as $k => $v) {
        if(is_array($v))
        {
            $string[$k] = $this->sanitize($v);
        }
        else
        {
            $string[$k] = $this->sanitizeSingle($v);
        }
 }

答案 1 :(得分:0)

通过一些小的调整,您可以利用php的native recursive functions中的一个来清理数组值。

class Sanitizer {
    public function sanitizeScalar(&$string) {  
        if (get_magic_quotes_gpc()) {
            $string = stripslashes($string);
        }
        $string = trim(htmlspecialchars($string, ENT_QUOTES)); 
    }

    public function sanitize($data) {
        if (is_array($data)) {
            array_walk_recursive($data, [$this, 'sanitizeScalar']);
        } else {
            $this->sanitizeScalar($data);
        }
        return $data;
    }
}

$array = ['one' => ['a ', ' b ', ' c'], 'two' => " <a href='test'>Test</a>"];
$string = ' another "test"';

$sanitizer = new Sanitizer();
var_export($sanitizer->sanitize($array));
echo "\n---\n";
var_export($sanitizer->sanitize($string));

输出:

array (
  'one' => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
  'two' => '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;',
)
---
'another &quot;test&quot;'

sanitizeScalar()通过引用修改输入字符串,以便对变量声明任何调整,并且没有return值。

sanitize()不能通过引用进行修改;修改后的数据已return编辑。