Link to home
Start Free TrialLog in
Avatar of Neil_Bradley
Neil_BradleyFlag for New Zealand

asked on

Destrot session

I have many sesssion variables and I would like to destroy all and keep one. Is this possible?
IE:
Destroy all session variables except $_SESSION['mySpecialSession'] ??
Thanks,
N
Avatar of Kalpan
Kalpan
Flag of India image

use the following

unset($_SESSION['other']);
ASKER CERTIFIED SOLUTION
Avatar of jimsweb
jimsweb
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pius_babbun
pius_babbun

To destroy the session completely you need to use session_destroy(); and to unset the session you need to use session_unset .

1.Since you need keep only $_SESSION['mySpecialSession'], u need to unset the all the other session  session_unset variables except this one.

2.The other options would to store only this value in $_COOKIES, so that you can destroy the other session values.

    foreach ($_SESSION as $key=>$val)
    if ( $key == "mySpecialSession" ) {
      echo "Not Deleting mySpecialSession";
    } else {
        unset ($_SESSION[$key]);
    };

This will work:

$temp = $_SESSION['mySpecialSession'];
$_SESSION = array();
$_SESSION['mySpecialSession'] = $temp;

Beware of the interaction of $_SESSION with register_globals.
http://php.net/manual/en/security.globals.php

Best regards, ~Ray
Add the following function:
 
function unset_session($exceptionVars = null)
{
	foreach ($_SESSION as $key => $value)
	{
		if ($exceptionVars != null)
		{
			//echo array_search($key, $exceptionVars);
			if (array_search($key, $exceptionVars) === false)
				unset($_SESSION[$key]);
		}
	}
}

Open in new window


To use it add you special variables in array and pass them to function as the following:
 
$exceptionVars[0] = "mySpecialSession";
$exceptionVars[1] = "anotherSpecialSessionVar";
unset_session($exceptionVars);

Open in new window

Avatar of Neil_Bradley

ASKER

Some interesting solution posted but in the end I used the simplest solution. I simply stored the session variable, destroyed the session then re opened it again before re creating my stored session.
If you used session_destroy() to destroy the session you may be in for some unpleasant surprises.  "Destroy" is a term of art when using PHP sessions.  Just be careful that your solution actually does what you think it will do.
Thanks Ray, back in the saddle this morning so will be testing the theory..
N