One thing you don’t always need to explicitly do is close a session. At the end of the script PHP takes care of it for you. There are times, though, when a call to session_write_close() is needed as well as times when using it can decrease your page load time.

What it does is ensure that all of the current session data is stored (in a file or database, depending on your set up) and unlocks the session for use.

After calling this function, any changes to the $_SESSION array will not be saved. That is, they will be there in the array for the remainder of the script but not the next time that session is used (even if the session is restarted in the same script).

$x = false;
session_start();
$_SESSION['test'] = "hello";
session_write_close();
$_SESSION['test'] = "goodbye";
$x = ("goodbye" == $_SESSION['test']);
session_start();
echo $_SESSION['test']; // hello
var_dump($x); // true

Redirecting

If you are redirecting the user, call this function beforehand. This will ensure that all the data manipulation you did with the $_SESSION array is recorded and available on future calls. I like to put it just before header() so it’s easy to see later on.

When Using Framesets

Only one script can access a session at a time. So if you have multiple frames using the same session, one can work while the others wait for the session to be unlocked.

In this situation, a call to session_write_close() when you’re done manipulating the session data in a script will free the session to be used sooner by the other script calls. The end result is the frameset being more efficient and loading quicker for the end user.

Stopping and Starting

As shown in the sample code above, you can start up a session again after closing it. Simply call session_start() but only if no output has been sent. Use output buffering if needed.