How to destroy a specific session?

Asked

Viewed 27,161 times

8

Here’s the thing: I have an application/game that uses sessions to memorize the data that users have chosen.

Whenever the user restarts the game I need to reset the information, so was using perfectly the

     session_destroy();

until I had to use

$_SESSION['email'] e $_SESSION['senha']

so that the user only had access to the game page if he was logged in.

So now if I use the

session_destroy();

sessions that keep the user logged in are also destroyed and he is redirected to the home page.

I tried to use

unset(); 

to empty only the sessions I need to restart, but then the system does not work properly. Sometimes I have to keep pressing the reset button several times...

Any suggestions?

Look what I’m doing:

      if ($_POST['entrada'] === "ex" ) //primeiro if
      {

          if(isset($_SESSION['palavra']))
           {
              unset($_SESSION['palavra']); 
           }

          if(isset($_SESSION['sessoes']))
          {
           unset($_SESSION['sessoes']); 
          }              
         if(isset($_SESSION['letra']))   
         {
          unset($_SESSION['letra']); 
         }


      }//fecha o primeiro if

Inside this main if are more than ten sessions to unsetar, I put only three to exemplify what I’m doing.

VAR DUMP no $_SESSION: array(13) { ["background"]=> string(5) "background" ["email"]=> string(25) "[email protected]" ["password"]=> string(8) "deusdeus" ["class"]=> string(7) "input" ["count"]=> int(3) ["pos"]=> int(0) ["pos_2"]=> int(2) ["error"]=> string(1) "v" ["erro_1"]=> string(1) "m" ["erro_2"]=> string(1) "w" ["erro_3"]=> string(1) "x" ["erro_4"]=> string(1) "z" ["erro_5"]=> string(1) "y" }

  • What is inside the $_SESSION for each user, and what needs to be deleted? It is yes the case to use unset, but only for the data you don’t need to keep (and not for the entire user session).

  • I used unset in all sessions that I need to delete when restarting the game. However, it doesn’t always work immediately. Sometimes I have to keep clicking one, two, three times on the restart button. It gives the impression that by clicking the button I am deleting the sessions. However all sessions that I need to delete are within an if, so if the condition is true (in this case, if the restart button is clicked) all those sessions will be unset.

  • It is unclear what you are calling "the sessions". There is only one session per user. And within it there is a lot of data. You can [Edit] your question and include the output of var_dump($_SESSION) for any user?

  • I explained that before using session to log in I was already using sessions in my game. I asked a few questions.

  • @Iwannaknow would be more logical to simply reset the game variables only instead of destroying the session.

  • 1

    You can split game variables, for example, $_SESSION['jogo']['palavra'] etc.. $_SESSION['jogo'] would be an array. Then when you need to clean just clear this whole key, with everything inside.

  • @bfvaretto I put the var dump in the question, are several sessions... Bacco And as zero the game variables? But I already say that many variables are stored in sessions precisely because I cannot lose data when user refresh page.

  • Clarifying the terminology, the session is one per user (even before logging in, consider the session as the browser window where your site is). For each session multiple variables can be associated, which are called "session variables". What you are calling "sessions" are "session variables".

  • @bfvaretto I read this just now on a forum. Anyway... Responding to your previous comment: if I understand you, I cannot do this because there are sessions that will only be set if others exist, that is, there are sessions that will not always exist. I can’t put them all in one array.

  • I think you can, just check what’s in $_SESSION['jogo'], instead of checking directly in $_SESSION.

  • In my code logic there are things that only happen if a session variable is set, in other cases if it is not. If I create an array with all variables inside I would be setting them all even if they were empty. Or not? Yes, but why did you suggest unsetting everything at once? Is there a bug if you try unsetar several session variables? I think you suggested what you thought was most practical...

  • Everything indicates that you are doing it in the right way. What I suggested is just a shortcut. If what you’re doing only works sometimes, it’s hard to know why without knowing your code better. For the part that’s posted, you can’t say.

  • Were you the one who wanted to make a game system for crossword? Can take advantage and give a more concrete example?

  • This "game" is actually to guess the word. But the problem is only in this very part, at the time of giving unset in the sessions. So much so that everything is working perfectly when I use session_destroy();

  • Does your code allow a full analysis? You can put it in the codepad to make it easier to identify the problem?

  • 1

    Dude, you asked for the code to do an analysis and I felt compelled to find some error that could be causing this and at the end I was forgetting to unsetar one of the session variables. There are so many... I’m sorry if I wasted someone’s time, but the code is all right, it was an oversight of mine alone. Thanks, your reply brings everything and can be useful for a visitor. @Papacharlie

  • I Wanna Know, arrange

Show 12 more comments

2 answers

6


Updating

You can do subgroups in the session:

$_SESSION['login'] = array( 'email' => '[email protected]' , 'senha' => 'userpassword' );
$_SESSION['games'] = array( 'palavra' => 'Helicóptero' , 'letra' => 'a' );

Your session will be in 2 groups: login data(email, password), and game data(word, letter...)

[login] => Array('email' => '[email protected]' , 'senha' => 'userpassword')
[games] => Array('palavra' => 'Helicóptero' , 'letra' => 'a' )

You can remove a specific Intel from the games session using unset( $_SESSION['games']['palavra'] ) or to restart the game you remove the full session of the game using unset( $_SESSION['games'] ), this will keep the user session unchanged.


Removing indices from Session

Unset unlocked a session variable, while session_destroy() will destroy all sessions for the user.

unset( $_SESSION['palavra'] );  // irá remover apenas os dados de 'palavra'
session_destroy();  // irá remover todas as sessões do usuário.

I don’t know if it’ll satisfy your doubt, but I’m just a simple example...

// criando sessões de login
session_start();
$email = $_SESSION['email'];
$senha = $_SESSION['senha'];

// criando sessões do jogo
$senha = $_SESSION['palavra'];
$senha = $_SESSION['letra'];

// removendo todas as sessões
session_start();
session_destroy();
unset( $_SESSION );

// removendo sessões do jogo
// opção 1)
unset( $_SESSION['palavra'] );
unset( $_SESSION['senha'] );

// opção 2)
$_SESSION['palavra'] = null;
$_SESSION['senha'] = null;

Masta you use as condition in each Session you need to check.

  • That’s what I’m doing. Suppose $_SESSION['word']=home; then I do unset( $_SESSION['word'] ); but then I need to add a new word within the $_SESSION['word']. Similarly I need to add new letters in each section responsible for storing a letter.

  • I posted on the question how I am unseating the sessions within an if. I must do an if for each session I want to unsetar?

  • It depends on which session you want to delete. Apparently it will be manually for each input.

5

You can do it like this:

session_start();
$tmpemail = $_SESSION['email'];
$tmpsenha = $_SESSION['senha'];
session_destroy();
session_start();
$_SESSION['email'] = $tmpemail;
$_SESSION['senha'] = $tmpsenha;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.