tags:

views:

180

answers:

4

Hello,

I'm having some trouble understanding PHP's sessions. First off I am saving session data in a database, I used PHP's session_set_save_handler() function to define that.

The way I understand when PHP saves the session data to the DB is like so:

If I define some session variables then output some text to the user's browser, I believe the session data is not saved to the DB until after the text is output. Please look at this bit of code:

$_SESSION['username'] = "$username";


//check if session variable set
if($_SESSION['username'] != $username)
{
die('error...');
}

In the code the if statement returns false so die() never occurs. Also PHP does not write the session data to the DB until after the if statement. What I don't understand is if the session data is not written to the DB yet, how is PHP comparing $_SESSION['username'] to $username? Is $_SESSION['username'] stored in server memory until the end of the script when session data is written to the DB?

Thank you for your time.

+2  A: 

Exactly right.

Session data is kept in-memory until the end of the request (or until session_write_close() is called). The contents of $_SESSION are then written to the configured storage mechanism.

On the next request, when session_start() happens, the data are loaded from storage to $_SESSION, where they stay, until the request is finished.

Otherwise, PHP would be reading/writing to the database (in your case) every time you touched anything in session.

timdev
+2  A: 

_SESSION is an "ordinary" array, like $a = array() is.
The "magic" only happens when session_start() is called and previously stored data is read (back) to _SESSION and when the session mechanism stops (when the php instance shuts down or when session_write_close() is called) and the data in _SESSION is serialized and stored.

VolkerK
+1  A: 

You can use a session_write_close to force php to write the session.

See : http://us2.php.net/manual/en/function.session-write-close.php

Sky's The Limit Software
A: 

Ok, this helps make sense of some things. Thank you for the quick replies everybody : )

lanmind