14

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 know trim($_POST) won't do, I have to make some function like

function sanatize_post(){
    foreach ($_POST as $key => $val)
        $_POST[$key] = trim($val);
}

But, if you have any other suggestion or comment, please help me.

Thanks

I-M-JM
  • 15,732
  • 26
  • 77
  • 103
  • If you are writing a library or a framework then you should provide more than `trim`. Otherwise, for a single page or a specific project you should not blindly process the entire `$_POST`. You should know exactly what values you need from `$_POST[]`, get only them and process each one in its specific ways (f.e., some value might be a number; converting it to integer or float is better than just trimming the whitespaces). – axiac Sep 15 '16 at 08:22
  • @axiac - is there any situation where blindly applying trim to all post values would cause some undesireable side-effect? I mean, assuming you 'know' that you don't want to retain whitespace at either end of any field. – ToolmakerSteve Feb 25 '19 at 00:35

8 Answers8

16

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;
    }
T.Todua
  • 53,146
  • 19
  • 236
  • 237
14

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']);
Mike
  • 23,542
  • 14
  • 76
  • 87
10

use array_walk with a custom function

$clean_values = array();
array_walk($_POST, 'sanitize_post');

function sanitize_post($item, $key)
{
    $clean_values[$key] = trim($item);
    //optional further cleaning ex) htmlentities
}
brian_d
  • 11,190
  • 5
  • 47
  • 72
  • 2
    Using `array_walk_recursive` instead of `array_walk` would cover the case when fields are grouped in the form. – Adam May 10 '16 at 14:20
  • @brian_d In this answer you have written a custom function accepting params $tem and $key, how are they passed to the function??? – Swapnil Shende Jul 14 '16 at 11:59
8

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

chx
  • 11,270
  • 7
  • 55
  • 129
  • 2
    There is also its' recursive kin http://php.net/manual/en/function.array-walk-recursive.php – nikc.org Jan 17 '11 at 06:15
  • can you please explain me what do you mean by "(note that this and the idea might be broken as input name=foo[bar] is translated into an array)" – I-M-JM Jan 17 '11 at 06:46
  • This solution does not work, because trim will be called on each array element, but the array element itself will not change. You would need to write a custom function something like: `function custom(&$a){ $a= trim($a);}`. – Adam May 10 '16 at 14:13
2

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');
kjdion84
  • 9,552
  • 8
  • 60
  • 87
1

Simply use this:

array_walk($_POST, create_function('&$val', '$val = trim($val);')); 

and your $_POST is now trimmed.

navid
  • 566
  • 6
  • 15
Nabeel Khan
  • 3,715
  • 2
  • 24
  • 37
1

I think it's better to use anonymous functions :

array_walk($_POST, function(& $value){
    $value = trim($value);
});
Az.Youness
  • 2,167
  • 1
  • 24
  • 33
1

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);
            }
        }
    }
}
Goose
  • 4,764
  • 5
  • 45
  • 84
  • 1
    I like seeing the recursion explicitly - then I know exactly what the code does. However, for anyone coming here, an alternative is to use `array_walk_recursive` - substitute it into one of the answers above that uses `array_walk`. OR [recursively apply array_map](https://stackoverflow.com/a/39637749/199364), so you don't have to write recursion yourself. – ToolmakerSteve Feb 25 '19 at 00:31