Need you help in an unusal situation. I need to trim all the $_POST variables.
Is there any way I can do it at a single shot i.e., using a single function?
I
You can also use this code I wrote in case you want to sanitize a string OR an array with one function:
function sanitize ($value) {
// sanitize array or string values
if (is_array($value)) {
array_walk_recursive($value, 'sanitize_value');
}
else {
sanitize_value($value);
}
return $value;
}
function sanitize_value (&$value) {
$value = trim(htmlspecialchars($value));
}
Simply use it like this:
$post_sanitized = sanitize($_POST);
$apple_sanitized = sanitize('apple');
array_walk($_POST, 'trim')
(note that this and the idea might be broken as input name=foo[bar] is translated into an array)
Edit: the above is not correct. Try $_POST = array_map('trim', $_POST);
.
Simply
$_POST = array_map("trim", $_POST);
But if $_POST members (even if 1 of them) is again an array itself, then use recursive version:
function array_map_deep( $value, $callback )
{
if ( is_array( $value ) ) {
foreach ( $value as $index => $item ) {
$value[ $index ] = array_map_deep( $item, $callback );
}
} elseif ( is_object( $value ) ) {
$object_vars = get_object_vars( $value );
foreach ( $object_vars as $property_name => $property_value ) {
$value->$property_name = array_map_deep( $property_value, $callback );
}
} else {
$value = call_user_func( $callback, $value );
}
return $value;
}
The other answers did not work well with associative arrays. This recursive functions will trim all values inside a $_POST array all levels down.
// Trim all values of associative array
function trim_associative_array(&$input_array) {
if (is_array($input_array)) {
foreach ($input_array as $key => &$val) {
if (is_array($val)) {
trim_associative_array($val);
} else {
$input_array[$key] = trim($val);
}
}
}
}
Here's a one-liner that will also work either on single values or recursively on arrays:
$_POST = filter_var($_POST, \FILTER_CALLBACK, ['options' => 'trim']);
I think it's better to use anonymous functions :
array_walk($_POST, function(& $value){
$value = trim($value);
});