note 107273 added to function.session-unset
| From: | Solomon | Date: | Thu, 26 Jan 2012 13:33:03 +0000 |
| Subject: | note 107273 added to function.session-unset | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-185754@lists.php.net to get a copy of this message | ||
Because I needed to leave a user logged in but also needed to clear a session of temporarily used
variables, session_unset was a little too heavy handed. Instead I wrote this this simple little
function to fit the bill - it allows you to retain certain session variables whilst unsetting
everything else. I hope it's useful for someone.
<?php
session_start();
$_SESSION['1'] = "One";
$_SESSION['2'] = "Two";
$_SESSION['3'] = "Three";
$_SESSION['4'] = "Four";
$_SESSION['5'] = "Five";
$_SESSION['6'] = "Six";
$_SESSION['7'] = "Seven";
$_SESSION['8'] = "Eight";
$_SESSION['9'] = "Motorway";
print_r($_SESSION);
# you can tell the function to hang on to particular session variables
$success = session_unset_partial(array('2','4','6','8'));
if ($success){echo "Array partially cleared.\n";}
print_r($_SESSION);
# or you can tell it to wipe everything but the required permanent session variables
$success = session_unset_partial();
if ($success){echo "Array partially cleared.\n";}
print_r($_SESSION);
function session_unset_partial($UserDontUnsetThese = false){
# quick error check
if ($UserDontUnsetThese && !is_array($UserDontUnsetThese)){
echo "Array expected for user-defined session variables\n";
return false;
}
# list set session vars that should not be unset here
# the ones listed here allow the user to remain
# logged in whilst all other temporary session
# variables are deleted
$DontUnsetThese = array (
'9'
);
if ($UserDontUnsetThese){
# combine the permanent array with the user-requested session variables
# to create a list of session variables that should be retained
$DontUnsetThese = array_merge($DontUnsetThese , $UserDontUnsetThese);
}
# now do the unsetting
foreach ($_SESSION as $key => $value){
if (!in_array($key , $DontUnsetThese)){
unset($_SESSION[$key]);
}
}
return true;
}
?>
----
Server IP: 92.48.74.199
Probable Submitter: 188.222.76.202
----
Manual Page -- http://www.php.net/manual/en/function.session-unset.php
Edit -- https://master.php.net/note/edit/107273
Del: integrated -- https://master.php.net/note/delete/107273/integrated
Del: useless -- https://master.php.net/note/delete/107273/useless
Del: bad code -- https://master.php.net/note/delete/107273/bad+code
Del: spam -- https://master.php.net/note/delete/107273/spam
Del: non-english -- https://master.php.net/note/delete/107273/non-english
Del: in docs -- https://master.php.net/note/delete/107273/in+docs
Del: other reasons-- https://master.php.net/note/delete/107273
Reject -- https://master.php.net/note/reject/107273
Search -- https://master.php.net/manage/user-notes.php