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

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.

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.

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.

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));
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.