Unset all session variables with similar name

时间秒杀一切 提交于 2020-01-30 12:00:48

问题


I'm using some $_SESSION variables for filtering many query records that have a similar name (ex. $_SESSION['nameFilter'] or $_SESSION['cityFilter'] and so on).

I'm using a link for resetting these filters, but I want to know if there is a way to unset all $_SESSION variables that have a name that is like:

$_SESSION[(somewords)Filter]


回答1:


Use foreach to enumerate the keys of $_SESSION[], use substr() to get the last 6 characters of each key, use unset() to (what else?) unset it.

As easy as:

session_start();
foreach (array_keys($_SESSION) as $key) {
    if (substr($key, -6) == 'Filter') {
        unset($_SESSION[$key]);
    }
}



回答2:


Assuming your keys always cointain the string Filter you can check for it.

I suggest you to take a look at the strpos function which checks if a given needle is cointaned in a string and returns the null in case it's not found or the position of where the needle starts in that string.

Then you only have to go through the session variables and unset the ones containing the word Filter

foreach($_SESSION as $key => $value){
  if (strpos($key, 'Filter') !== false) {
    unset($_SESSION[$key]);
  }
}

Hope this helps :)




回答3:


You need to check for every exist session and check it name. Please check below example code.

<?php
session_start();

//Example records...
$_SESSION['onefilter'] = 'one';
$_SESSION['twofilter'] = 'two';
$_SESSION['threefilter'] = 'three';
$_SESSION['fourtilter'] = 'four';

//Loop untill exist session...
foreach($_SESSION AS $sessKey => $sessValue){
    //Check for session name exist with 'filter' text...
    if (strpos($sessKey, 'filter') !== false) {
        unset($_SESSION[$sessKey]);//Unset session
    }
}

echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
/*Output...

Array
(
    [fourtilter] => four
)
*/
?>

May this help you well.




回答4:


Steps :

1.) Get all session variable using $_SESSION.
2.) Check in every session key if it contain "Filter" string 
then unset it using unset($_SESSION[(someword)Filter]);

Try this :

foreach($_SESSION as $key => $value){
  if (strstr($key, 'Filter') == 'Filter') {
    unset($_SESSION[$key]);
  }
}


来源:https://stackoverflow.com/questions/35082899/unset-all-session-variables-with-similar-name

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