Jim Fell
Jim Fell

Reputation: 14256

PHP Session Not Restoring from Cookies

When a user returns to my website, it attempts to restore their last session from the $_COOKIE associative array. It's not working as expected. I can look in my browser's cookie manager and see that the cookies are there, but they don't seem to be getting saved to the $_SESSION associative array.

This is essentially the program flow when a user returns to my site:

foreach ( $_COOKIE as $name => $val )
{
  $_SESSION[$name] = $val;
}

session_start();

...

$some_var = $_SESSION[$var_name];

Do I have things out of order, or should I not be overwriting PHPSESSID? Any insight as to what I'm doing wrong would be appreciated. Thanks.

Upvotes: 0

Views: 1300

Answers (2)

Mark
Mark

Reputation: 1852

You're getting sessions and cookies mixed up. You don't need to put things into the $_COOKIE array. Just use session_start() and then put things into $_SESSION. PHP will automatically then manage the session/cookie for you.

$_COOKIE variables are stored on the users browser, so they aren't secure and can be manipulated by the user => security risk.

$_SESSION variables are stored only on the server. The only thing stored in the cookie is a session_id, so $_SESSION variable can't be manipulated.

Does that make sense?

Upvotes: 2

jcmeloni
jcmeloni

Reputation: 1234

Put session_start() before anything else; this function initializes the session data that you will be accessing in $_SESSION.

Not exactly sure what you're trying to achieve with the rest of it all, but session_start() first is a starting point...

Upvotes: 1

Related Questions