Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP need to trim all the $_POST variables

Tags:

php

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

like image 948
I-M-JM Avatar asked Jan 17 '11 06:01

I-M-JM


People also ask

Why TRIM () function is used in PHP?

Definition and Usage. The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.

What is $_ POST []?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post".

What are post variables?

The $_POST variable is an array of variable names and values sent by the HTTP POST method. The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.


2 Answers

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;
    }
like image 118
T.Todua Avatar answered Sep 20 '22 21:09

T.Todua


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']);
like image 42
Mike Avatar answered Sep 18 '22 21:09

Mike