PHP Session Store
I am having trouble understanding PHP sessions. First, I am storing the session data in the database, I used a PHP function session_set_save_handler()
to determine this.
The way I understand it, when PHP saves session data to DB looks like this:
If I define some session variables, then we output the text to the user browser, I believe that the session data is not saved in the DB until the text is displayed. 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 it die()
never occurs. Also, PHP does not write session data to the database until an if statement is given. I don't understand if the session data hasn't been written to the DB yet, how does PHP compare $_SESSION['username']
with $username
? Is it kept $_SESSION['username']
in server memory until the end of the script when session data is written to the DB?
Thank you for your time.
source to share
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 engine.
On the next request, when session_start () occurs, the data is loaded from storage into $ _SESSION, where it remains until the request is complete.
Otherwise PHP will read / write to the database (in your case) every time you touch anything in the session.
source to share
_SESSION is a "regular" array, for example $a = array()
.
The "magic" only happens when session_start () is called and the previously saved data is read (back) to the _SESSION and when the session engine is stopped (when the php instance is shut down or session_write_close () is called) and the data in _SESSION is serialized and saved.
source to share
You can use session_write_close to force php to write session.
See http://us2.php.net/manual/en/function.session-write-close.php
source to share