2

I am new to learning Php. I have created the following code.

<?php /* * Testing Sessions with PHP */ session_start(); $_SESSION['user_id'] = 'Testing User'; session_destroy(); ?> <html> <head> <title> Sessions Page</title> </head> <body> <?php echo $_SESSION['user_id']; ?> </body> </html> 

Now the echo $_SESSION['user_id'] echos testing user. In my opinion it should not, as i have destroyed the session. what is the reason?

4 Answers 4

2

You need to unset the session vars. See http://php.net/manual/de/function.session-unset.php

Means, put session_unset() before you destroy the session.

Sign up to request clarification or add additional context in comments.

4 Comments

Great! it worked but, what is the difference between session_unset() and session_destroy() ?
The question still remains there in my mind. When the session has been destroyed why do session variables exist. This does not connect to logic at least for me. Please elaborate if you can.
The vars are already initialized. If you reload the page, this vars are gone. With or without session_unset(). You need this to get rid of the vars without reloading the page.
2

The function session_destroy() will indeed destroy your session. The session is in this case the file (or db) on the server, holding your data. That means you cannot access this session on other pages afterwards.

The globale $_SESSION[] variable is a different story. It is filled from the session file, before the code on your page starts processing. Therefore it holds a copy of the data and stays in memory until your page has finished processing. You can clear this variable with session_unset(), but as well you can wait until the page has finished and all it's variables are destroyed anyway.

Comments

1

This appears to be (for whatever reason) by design. The correct way to do what you wish is.

session_start(); $_SESSION['user_id'] = 'Testing User'; session_unset(); session_destroy(); 

This code will remove all session variables from $_SESSION and then destroy the session.

Comments

0

Need to be more comprehensive as PHP sessions can really behave differently. The following works perfectly in all browsers to kill/destroy/unset all session info. Perfect to be used in sign-out file.

<?php session_start(); session_unset(); session_destroy(); session_write_close(); setcookie(session_name(),'',0,'/'); session_regenerate_id(true); ?> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.