Drupal stores its persistent $_SESSION data in the 'session' column of the 'sessions' table in the database.
My question is: how exactly is this data serialized and unserialized? A regular PHP unserialize() function returns a Warning/Error because it isn't in the correct format.
Unserialized data:
Array ( [test] => 13:58:32 [test_change_no] => 0 [a] => Array ( [b] => Array ( [c] => abc ) ) )
How it's stored in the database:
test|s:8:"13:58:32";test_change_no|i:0;a|a:1:{s:1:"b";a:1:{s:1:"c";s:3:"abc";}}
Return value of PHP serialize() on the unserialized data:
a:3:{s:4:"test";s:8:"13:58:32";s:14:"test_change_no";i:0;s:1:"a";a:1:{s:1:"b";a:1:{s:1:"c";s:3:"abc";}}}
I need to know how to unserialize & serialize data in the format which Drupal uses. Thanks.
Comments
I'm not 100% sure on this
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.
You're right about this
PHP does some weird internal magic to serialize & unserialize the data. The weird part is that it uses a serialization method slightly different from the regular serialize() & unserialize() PHP functions (like you'd expect).
I think it assumes the $_SESSION is always an array and serializes the data in the following manner:
{variable_key_1}|serialize($variable_value_1){variable_key_2}|serialize($variable_value_2){variable_key_3}|serialize($variable_value_3)... and so on where the "|" (pipe) character acts as a token of some kind.
It also depends on the session.serialize_handler directive (php.ini).
From the manual:
session.serialize_handler defines the name of the handler which is used to serialize/deserialize data. Currently, a PHP internal format (name php) and WDDX is supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. Defaults to php. (emphasis mine)
Nothing to do with Drupal really, it's a PHP quirk. Learn to love it~ ;)
Nothing too mysterious here,
Nothing too mysterious here, it uses session_encode/session_decode, have a look:
http://www.php.net/manual/en/function.session-encode.php
Cheers