PixelsTech
PixelsTech

Reputation: 3347

What does session_destroy() do in PHP?

In PHP manual, the description for session_destroy() function is :

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

I am confused about this description. If this function destroys all session data, then why the global variables associated with the session are not unset? Why can we use the session variables again?

Upvotes: 6

Views: 5898

Answers (2)

user1129665
user1129665

Reputation:

session_destroy() deletes the session file where session data are 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 set 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 name similar to sess_4r7ldo7s5hsctu3fgtvfmf4sd0. This is where session data is being stored and it will contains:

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 be simply deleted.

Upvotes: 2

hakre
hakre

Reputation: 197682

I am confused about this description. If this [session_destroy()] function destroys all session data, then why the global variables associated with the session are not unset? Why can we use the session variables again?

Session data is the data associated with the session. The session is defined by its name (the session name) and its id (the session id).

By using that function, all this sessions (name + id) data is destroyed.

The variable container which allowed you to read / set that data is still there, so you can operate on that data (e.g. there might be information in like last activity and this is a logout and you want to store the last activity know at logout or so into some logs or database, so why delete it? that would be counter productive because you want to destroy (or commit) sessions fast, e.g. when you know read-only access is needed only, keep the session data in memory, but commit the session already because there is no need to keep it open).

Keep in mind that even these variables are access via $_SESSION they are not part of the session any longer. Perhaps that is the confusing part?

BTW my description is not totally correct. PHP internally identifies the session data by the id only so you could change the session name and session_destroy() would still remove the session data because the session id has not changed.

Upvotes: 5

Related Questions