What does session_destroy () do in PHP?

In the PHP manual, description of session_destroy () :

session_destroy () destroys all data associated with the current session. It does not cancel any global variables associated with the session, or does not delete the session cookie. To use session variables again, you must call session_start ().

I am confused by this description. If this function destroys all session data, why aren't the global variables associated with the session canceled? Why can we use session variables again?

+6
source share
2 answers

I am confused by this description. If this function [ session_destroy() ] destroys all session data, then why aren't the global variables associated with the session canceled? Why can we use session variables again?

Session data is the data associated with a session. A session is determined by its name (session name) and its id (session identifier).

Using this function, all these sessions (name + id) are destroyed.

The variable container that allowed you to read / set this data still exists, so you can work with this data (for example, there may be information in the form of the last action, and this is logout, and you want to save information about the last event when logout or in some logs or in the database, so why delete them? It will be counterproductive because you want to quickly destroy (or make) sessions, for example, when you know only read-only access, save session data sa in memory, but end the session already because there is no need to keep it open).

Keep in mind that even these variables are available through $_SESSION , they are no longer part of the session. Perhaps this is the confusing part?

By the way, my description is not entirely correct. PHP internally identifies session data by identifier only so that you can change the name of the session, and session_destroy() would still delete the session data because the session identifier has not changed.

+5
source

session_destroy() deletes the session file in which the session data is stored. Look here:

 <?php session_save_path('./session/'); session_start(); $_SESSION['v'] = array( 'foo' => 123, 'bar' => 'spam' ); $_SESSION['m'] = "rocky"; if( isset($_GET['delete']) == 'true' ) session_destroy(); ?> 

I have a script whitch creates a session and sets the value of v to 10 , and it saves the session data in the same script path in a folder named ./session .

Now open the page and then browse the ./session directory, you should see a file with a name similar to sess_4r7ldo7s5hsctu3fgtvfmf4sd0 . Session data is stored here and it will contain:

 v|a:2:{s:3:"foo";i:123;s:3:"bar";s:4:"spam";}m|s:5:"rocky"; 

Activate session_destroy() by passing ?delete=true to the page, the session file will simply be deleted.

+1
source

Source: https://habr.com/ru/post/952879/


All Articles