Dreb Bits

Tag: Security

Sanitize Multidimensional Input Field

Since input can accept multidimensional reference such as name="foo[bar]" or name="foo[bar][inside], you should sanitize/escape values multidimensional array recursively from the POST action.

With WordPress’s sanitize_text_field, here’s a gist:

function sanitize_array( &$array ) {

    foreach ($array as &$value) {   

        if( !is_array($value) ) 

            // sanitize if value is not an array
            $value = sanitize_text_field( $value );


            // go inside this function again


    return $array;


Here’s a sample usage:

// Var
$arrayName = array('foo' => 'Hello to the', 'bar' => array('var1' => '<strong>Bold</strong>', 'var2' => 'World!'));

// Usage
$return = sanitize_array($arrayName);

// DB insertion
$return = maybe_serialize( sanitize_array($arrayName) );

Link to raw file