Destroy session, but keep one variable set
I am using session varia开发者_运维技巧bles to control logins and page access. I use variables to control different user groups that a user belongs to, so I have quite a few session variables.
I also use a session variable to remember the users last visited page upon refresh.
When the user logs out, I use session_destroy(); to remove all variables. What i would like to do is to maintain the last visited page variable even after the user has logged out.
I think I could do it by using the unset function on every other variable, but there are a lot, and was wondering if there was an easier way?
Thanks Eds
you can try below code for this,
$Arr_not_destoy_session = array('last_visited_id');
foreach($_SESSION as $sees_key => $sess_val ){
if(!in_array($sees_key, $Arr_not_destoy_session)){
unset($_SESSION[$sees_key]);
}
}
this will unset all the session variables except 'last_visited_id' only.you can also add more values in this array which you dont want to remove later on..
Thanks.
Well you can destroy the session but before doing so, save the last page into a variable that you will be putting in a new session variable.
$lastPage = $_SESSION['last_page'] $session_destroy(); then create a new session with the $lastPage in it.
Another way is to save the last page the user visited into the user record of your db. (this will make it accessible from everywhere and it wont be location specific)
Going back to your existing fall-back solution of using unset()
, you say the issue with this is that there are a lot, but that shouldn't make it difficult; I still think this is a good solution to your problem.
Firstly, you could unset them all using a foreach()
loop; this would only need a few lines of code:
foreach($_SESSION as $key=>$value) {
if($key != "the_one_you_want_to_keep") {
unset($_SESSION[$key]);
}
}
Another way of doing it would be to organise your session data in sub-arrays, so that you can then clear them out by unsetting the single top-level array variable, but leaving the other session data in other sub-arrays untouched:
unset($_SESSION['user_data']);
//but don't unset $_SESSION['data_to_keep']
Hope that helps.
Try to group you session variables in arrays and to unset them you'll just need to unset the one or several arrays in $_SESSION
. For example if you keep the user info in the session, try this:
$_SESSION['user_info'] = array(...);
$_SESSION['last_visited_page'] = '...';
After logout you can just unset $_SESSION['user_info']
and keep the $_SESSION['last_visited_page']
精彩评论