PHP Session Not Restoring from Cookies

不打扰是莪最后的温柔 提交于 2019-12-12 03:17:49

问题


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.


回答1:


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?




回答2:


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...



来源:https://stackoverflow.com/questions/9087919/php-session-not-restoring-from-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!