开发者

hook_user op load does not fire?

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:

  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜