I have the following code in a custom module to save a session_id for comparison after logging in. I want to add it to the user object, so I called hook_user like so:
function mymodule_init() {
global $user;
if ($user->uid == 0 && !isset($_SESSION['anonymous_session_id'])) {
$_SESSION['anonymous_session_id'] = session_id();
}
}
function mymodule_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
case 'load':
$user->anonymous_session_id = $_SESSION['anonymous_session_id'];
break;
default:
break;
}
}
However, it is not in the user object. There is a ‘session’ field that has a serialized array of $_SESSION information, which would mean I probably don’t need hook_user, but why isn’t this code working?
There are two issues you’re running into:
hook_user()isn’t in$user(it’s not one of the parameters): it’s actually in$account.$userobject isn’t fully loaded even after modifying$accountduringhook_user()(See related issue).To get the fully loaded user object, do this:
One thing to keep in mind is that, unless you run
user_save(), information added to the$userobject duringhook_user($op = 'load')does not transfer from page to page:hook_user()is called every time the user is loaded, which is at least once a page. If you want to maintain session information without using the database, use$_SESSION.