Rakesh K
Rakesh K

Reputation: 712

Issue with session_start and session_write_close

Below code gives me outupt as name xxxxx. while as per documentation session_write_close closes the session.

Kindly help me understanding this.

session_start();

$_SESSION['name'] = "xxxxx";

session_write_close();

print_r($_SESSION);

Upvotes: 2

Views: 1189

Answers (5)

theking2
theking2

Reputation: 2837

Others have pointed out that session_write_close != session_destroy but what is the use of session_write_close than if not ending the session?

Sessions are persistant

Session data normally persists between multiple calls to the the same (web)server. Therefor this data has to be stored on the server somehow. This is governed by the option session_storege_handler so you could do anything with the session data to have it persist through different sessions, like storing it in a database or some other interprocess call but by default it will store this in a per session file. The file is normally deleted after some timeout or when calling session_destroy()

Not Persistent anymnore

But with session_write_close this function is called the current session data is stored (as | separated sting in the sess_file) and that is it. After that you are free to add additional data to the session, they are simply not persistant anymore. This is great if you have to share some data during the current session only, like storing results of some complicated calculation that you want to perform only once but don't want it to be stored on server side.

TL:DR

session_write_close refers to writing the session data on the server side and closing this file. After that all $_SESSION data and changes/additions to it are available not no longer persistant.

Upvotes: 1

xdazz
xdazz

Reputation: 160883

Other answers mentioned you by session_destroy() to destroy the session, but note it does not unset any of the global variables associated with the session, or unset the session cookie.

You have to use the below:

// Unset all of the session variables.
$_SESSION = array();

Upvotes: 1

Dinesh Babu
Dinesh Babu

Reputation: 456

You can unset the session using

unset($_SESSION['session_name']);

Upvotes: 1

Rikesh
Rikesh

Reputation: 26441

session_write_close != session-destroy

Definition:

End the current session and store session data. Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

Upvotes: 3

Gowri
Gowri

Reputation: 1856

If you want to destroy the session use session_destroy();

Upvotes: 1

Related Questions