tags:

views:

169

answers:

3

Every time I access data in $_SESSION, Does it immediately update the session file on the disk, or just once when the process goes down? Or every n bytes of data change (flush)?

This question is not necessarily about the specific file session handler, but every handler. (Does every touch in session immediately invoke an I/O of any kind, beside the storing of a normal variable in memory).

A: 

Depends on the handler. You can write your own handler to make sure it only happens as often as you like if you want to be absolutely sure about the behavior. There are 6 callbacks used to manage session variables. The one called "write" does not have to perform any real I/O and writing the session file could wait until the call to "close". It is an implementation detail that, as I said, depends on the handler.

jmucchiello
Say the process crash, I assume the unwritten session data is lost, correct?
Itay Moav
Yes, and presumably any uncommitted database actions are also lost.
jmucchiello
+2  A: 

It writes it and the end of the process on my setup. I made a new _ session_ write_method:

public function _session_write_method($id, $sess_data) {
    var_dump(file_put_contents('/var/www/public_html/testing.txt', serialize($sess_data)));
    return(true);
}

and then:

$_SESSION['foo'] = 'bar';
while(true)

I executed the script,waited a few seconds and then ran 'sudo kill' on the process id. It did not write the serialized data to the file. I ran it again without the infinite loop and I got: int(22) at the very bottom of the page and testing.txt was successfully written to and contained: s:14:"foo|s:3:"bar";";

Matt
+3  A: 

As Matt wrote, it writes at the end of script execution by default. You can read about it here in session_write_close()

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.

OIS