PHP -Sanitize values of a array

Depends what its being used for.

If you are inserting it into the database then mysql_real_escape_string() for quoted strings and type casting for numbers would be the way to go - well ideally prepared statements, but thats an entirely different matter.

If you plan on outputting the data onto the webpage then I would recommend something like htmlspecialchars()

If you plan on using the user input as a shell argument, then you would use escapeshellarg()

Moving onto your question about sending emails. Well, the following should suffice:

filter_var($_POST['message'], FILTER_SANITIZE_STRING);

All this does is basically strip tags and encode special characters.


Just use filter_input_array() from the filter extension.

/* prevent XSS. */
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

This will sanitize your $_GET and $_POST.


You can use strip_tags() with array_map()

<?php  
$a = array(
'title' => 'Title',
'data' => array(
    'hdr' => 'Header',
    'bdy' => 'Body'
    ),
'foo' => array(1, 23, 65)
);

$b = array_map("strip_tags", $a);
print_r($b);
?>

Update for 2D array:

function array_map_r( $func, $arr )
{
    $newArr = array();

    foreach( $arr as $key => $value )
    {
        $newArr[ $key ] = ( is_array( $value ) ? array_map_r( $func, $value ) : ( is_array($func) ? call_user_func_array($func, $value) : $func( $value ) ) );
    }

    return $newArr;
}

Usage:

$a = array(
'title' => 'Title',
'data' => array(
    'hdr' => 'Header',
    'bdy' => 'Body'
    ),
'foo' => array(1, 23, 65)
); 

$ar =array_map_r('strip_tags', $a);
print_r($ar);

Note I found this just by searching the comments for Dimension