TNK
TNK

Reputation: 4323

Storing all POST data in SESSION

I have more values (over 20) from $_POST like this...

$name = $_POST['name'];
$username = $_POST['username'];
$city = $_POST['city'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];

NOTE : I have prevented there values from SQL injection.

My question is can I know is there a way to store all these POST values in SESSION at once? Instead of this method..

$_SESSION['name'] = $name; etc

any answers will be highly appreciated. Thank you.

Upvotes: 11

Views: 64164

Answers (4)

Mirko Adari
Mirko Adari

Reputation: 5103

You can add one array to another.
$_POST and $_SESSION are just arrays.
Note that the keys in the second array take priority in case of duplicates.

$_SESSION += $_POST;

However, I don't see this ending well, since the client side can inject anything he wants to the session, E.G. hijacking your users session id.

Upvotes: 9

Mattt
Mattt

Reputation: 1779

$_SESSION['post-data'] = $_POST;

That will create an array of the post values in a single session variable. The values would be accessible as

$_SESSION['post-data']['name']
$_SESSION['post-data']['username']
...

Upvotes: 28

Jaro
Jaro

Reputation: 51

The best explanation of passing variables either with form post or header location redirection inside php check out my answer in this thread: How to pass variables received in GET string through a php header redirect?

Upvotes: 0

PhearOfRayne
PhearOfRayne

Reputation: 5050

If you looking for session variables that are set using the same key as the posted array, you could use this:

foreach ($_POST as $key => $value) {
    ${$key} = $value;
    $_SESSION[$key] = $value;
}

This will make your $_POST array into variables based on the array key and also set the session at the same time. You could then access your name post by using either $_SESSION['name'] or $name.

This means you will not need to use: $name = $_POST['name']; anymore. As the above code will set the name variable for you and also set the session variable.

Upvotes: 3

Related Questions