0

At times, I have need to push all submitted form array values into $_SESSION. To do this, I've written a small function:

function addPostToSession() {
     foreach ($_POST as $key=>$value ){

       $_SESSION[$key]=stripslashes(strval($value));
    }

   }

This works well, as long as $_POST is one dimensional, but in a form with checkboxes, $_POST may contain arrays as array elements.
Example:

POST: Array
(
    [othertype] => Server
    [issues] => Array
        (
            [0] => crashes
            [1] => freezes
        )

)

When I use my addPostToSession() function, $_SESSION['issues'] is given the string 'Array' (checked with var_dump).

Example:

    SESSION: Array
    (

        [othertype] => Server
        [issues] => Array

    )

Is there a preferred way to gather array values into $_SESSION without using implode or some other array-to-string function?

Thanks in advance,
-Ray

Edited by rsleventhal: clarity and examples

3
Contributors
4
Replies
18
Views
2 Years
Discussion Span
Last Post by cereal
2

Why not put the entire array in it at once?

$_SESSION['MyPostArray'] = $_POST;

Not a practice I'd recommend, but it works. You can do your sanity checks when you actually use the posted values.

0

I always cleanse and verify data before inserting or otherwise using it programatically, as you suggested. But thank you for the info. Shall try this and I do appreciate your reply.

0

In the end, I modified my addPostToSession() function thus:

function addPostToSession() {
     foreach ($_POST as $key=>$value ){
         if (is_array($_POST[$key])) {
             $_SESSION[$key]=$_POST[$key];
     } else {

       $_SESSION[$key]=stripslashes(strval($value));
    }

   }
}

Which, thanks to your input, does exactly what I needed.

0

Be aware with this solution: a client could overwrite any index of the $_SESSION array through the $_POST keys. For example, if you set the user id and the status in the session, like this:

$_SESSION['user_id'] = 34;
$_SESSION['is_logged'] = 1;

then a user can submit a form to your script with:

<input type="text" name="user_id" value="34" />
<input type="text" name="is_logged" value="1" />

and gain the access to any desired account without using a password. So, be sure to whitelist all the keys received through the $_POST array and submit to the session array only those allowed by your code:

$allowed = array('othertype', 'issues');

foreach($_POST as $key => $value)
{
    if(in_array($key, $allowed))
    {
        if(is_array($_POST[$key]))
            $_SESSION[$key] = $_POST[$key];

        else
            $_SESSION[$key] = stripslashes(strval($value));
    }
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.