Skip to content
Advertisement

Sanitize & desanitize multidimensional array

I have the following class I wrote:

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

}

The problem is that while it works on strings and one-dimensional arrays, I get the following error with multidimensional arrays:

Warning: htmlspecialchars() expects parameter 1 to be string, array given in C:wampwwwclassesSanitizer.php on line 10

How do I fix this? Any help would be greatly appreciated.

Advertisement

Answer

Your code was not evaluating array in $v Modify your foreach block like this, this modification will sanitize any level of nested array,

 foreach ($string as $k => $v) {
        if(is_array($v))
        {
            $string[$k] = $this->sanitize($v);
        }
        else
        {
            $string[$k] = $this->sanitizeSingle($v);
        }
 }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement