Unset all session variables with similar name

后端 未结 4 808
生来不讨喜
生来不讨喜 2021-01-24 08:55

I\'m using some $_SESSION variables for filtering many query records that have a similar name (ex. $_SESSION[\'nameFilter\'] or $_SESSION[\'cityF

相关标签:
4条回答
  • 2021-01-24 09:39

    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]);
        }
    }
    
    0 讨论(0)
  • 2021-01-24 09:41

    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 :)

    0 讨论(0)
  • 2021-01-24 09:48

    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.

    0 讨论(0)
  • 2021-01-24 09:48

    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]);
      }
    }
    
    0 讨论(0)
提交回复
热议问题