tags:

views:

72

answers:

1

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?

+4  A: 

There are two issues you're running into:

  1. The user object in hook_user() isn't in $user (it's not one of the parameters): it's actually in $account.
  2. The global $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.

Mark Trapp
Doh, totally did not notice $account. Been working with $user for 3 hours. The problem I am running into is when they log out, SESSION is regenerated and my custom value is lost there as well. I am trying to track a users actions on the site, from anon to auth (if they log in) and make sure they don't see a custom message twice.
Kevin
Essentially, I need to have Drupal know if a user has seen a message before. I don't want an anon user to close a message, then log in, and see the message again, vice versa.
Kevin
You need to create a cookie. See http://stackoverflow.com/questions/1317066/how-to-store-session-cookie-in-drupal-6-on-the-computer-of-the-visitor/1325651#1325651 You can't save anything in the user or session objects because both are destroyed upon logout.
Mark Trapp
Thank you, I will check that out.
Kevin

related questions