Dave
Dave

Reputation: 427

PHP merge $_POST into $_SESSION

Is there a way to take the $_POST data array and merge it into the $_SESSION array. I want it to keep the current data intact and only insert new data or update the pieces that have been changed. I've tried array_merge but it didn't do what I was looking for.

Thanks

Upvotes: 1

Views: 3001

Answers (4)

TimoSolo
TimoSolo

Reputation: 7325

array_merge does work, but it doesnt modify the array, it returns the merged array. What you want to do is:

$_SESSION = array_merge($_SESSION, $_POST);

(security warnings as above :)

Upvotes: 0

Marc B
Marc B

Reputation: 360572

foreach ($_POST as $key => $val) {
    if (!isset($_SESSION[$key]) || ($val !== $_SESSION[$key])) {
        $_SESSION[$key] = $val;
    }
}

in short, if the currently-being-considered POST key value doesn't have a corresponding entry in the SESSION arra, or the two values differ, then copy the POST data to SESSION.

However, be aware that this would allow malicious users to overwrite the entire session array. If they know that you keep a $_SESSION['is_admin'] flag, they can trivially overwrite it with an appropriate value and give themselves superuser powers.

Directly+blindly transferring user-provided data into the session variable is NEVER a good idea.

Upvotes: 1

Jonathan M
Jonathan M

Reputation: 17441

Not a good idea to try to merge $_POST into $_SESSION. Instead, do something like:

$_SESSION['lastPost']=$_POST;

Or, if you're wanting to update changes, compare $_POST with $_SESSION['lastPost'] and assign any differences to the affected keys, such as

$_SESSION['lastPost']['thisKeysValueChanged'] = $_POST['thisKeysValueChanged'];

Upvotes: 1

Simon H
Simon H

Reputation: 1745

Could you not try creating a $_SESSION['postVars'] variable and then storing the $_POST information in there. I wouldn't try and merge $_SESSION with $_POST that will have security implications for your application later on down the track. Having said that I would also be careful about just saving whatever comes through on the $_POST global. Anyway, I hope my suggestion helps.

Upvotes: 1

Related Questions