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.$user object isn't fully loaded even after modifying $account during hook_user() (See related issue).To get the fully loaded user object, do this:
global $user;
$account = user_load(array($user->uid));
One thing to keep in mind is that, unless you run user_save(), information added to the $user object during hook_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With