php session - destroy all sessions and keep only one active

3

Hello,

I need to destroy all sessions when logging out of a system, except for just one ... would anyone know how to implement this with php?

For example:

  • Let's say I have 5 active sessions when the user is logged in:

    $session1 = $_SESSION['session1'];
    $session2 = $_SESSION['session2'];
    $session3 = $_SESSION['session3'];
    $session4 = $_SESSION['session4'];
    $session5 = $_SESSION['session5'];
    
  • When I log out, I want to destroy 4 of these sessions, but there is one that I need to keep active ... how would it look like in this part? I tried it like this:

    session_start();
    
    if(!isset($_SESSION['session4'])){
    
          session_destroy(); 
    
    }//end if
    
    • so it did not work ... what would be the right one?
asked by anonymous 10.08.2018 / 19:07

3 answers

2

You are misunderstanding $ _SESSION represents the current session, it is an associative array with session data, $ _SESSION ['session1'] represents variable stored in that session.

to delete a session variable can do

unset($_SESSION['session1']);

to delete all variables

$_SESSION = array();

to delete all variables except the variable with the 'session1' key

foreach ($_SESSION as $key => $value) {

    if ($key != 'session1') {

        unset($_SESSION[$key]);

    }
}
    
10.08.2018 / 19:19
5

You could create a variable temporarily to receive the value of the session variable, destroy all and then create only the session variable you want.

$auxiliar = $_SESSION['session4'];

session_unset();

$_SESSION['session4'] = $auxiliar;

Another, more direct, way to do this:

$_SESSION = ['session4' => $_SESSION['session4']]
    
10.08.2018 / 19:19
0

You give session_destroy (); you will destroy all session, for you to destroy only the specific use unset ();

thus:

unset($_SESSION['session1'], $_SESSION['session2']);

RESULT: you will destroy the 2 session (or the ones you put inside unset ();

    
10.08.2018 / 19:33