Session Data in Drupal: DO NOT USE sess_read() and sess_write()!
When developing a module in Drupal, reading and writing session data is a fairly common pattern. However, it isn't immediately obvious what the best method is for doing this. If you need to read or write to the session in D6, the preferred method is to use the $_SESSION[] superglobal variable as follows:
<?php
function module_setsessionvar() {
// Write to the session
$_SESSION['module_sessionvar'] = 'example value';
}
function
module_getsessionvar() {
// Read from the session
$sessionvar = $_SESSION['module_sessionvar'];
}
?>Do not use the sess_write() and sess_read() Drupal core functions. Using these to manipulate session data will cause undesired side effects such as user logouts.
Comments
#1 Thanks for this post.
Submitted by Mc David (not verified) on Sun, 11/29/2009 - 11:44.
Thanks for this post.
#2 Hey, do you have any idea how
Submitted by chext0r (not verified) on Mon, 11/30/2009 - 09:26.
Hey, do you have any idea how Drupal's session data is serialized when it's stored in the database? And how does one unserialize it? PHP's serialize functions do not work
See http://drupal.org/node/646702 for more details. Any help is appreciated. Thanks
#3 I'm not 100% sure ...
Submitted by Eric Weik on Mon, 11/30/2009 - 15:33.
I'm not 100% sure on this one, but I believe that PHP actually handles the serialization, not Drupal.
Drupal registers its own session handlers (sess_read(), sess_write(), etc.) with a call to the PHP internal function session_set_save_handler() in includes/bootstrap.inc (see case DRUPAL_BOOTSTRAP_SESSION in _drupal_bootstrap().
Looking at the source to Drupal's session handler sess_write(), it looks to me like assumes the value passed to it is already serialized. It stores the key and value directly to the {session} table with an UPDATE query.
#4 Thank you
Submitted by Robin van Emden (not verified) on Mon, 12/07/2009 - 04:15.
Very useful!
#5 You are welcome!
Submitted by Eric Weik on Mon, 12/07/2009 - 21:46.
You are very welcome Robin. When I was first learning Drupal module development, this particular issue caused me some confusion (e.g. using sess_write() resulted in users randomly getting logged out), so I hope to save others some time and headache!
#6 Thanks for this info! I lost
Submitted by Venkat (not verified) on Sun, 06/20/2010 - 12:32.
Thanks for this info! I lost many hours confused as to why users were getting logged out.
Post new comment