On our site we have client accounts, each with a super administrator and sub users belonging to that account.

We want the super admin to be able to force sub users to log out. What's the best way to destroy a user's session in Drupal that works regardless of whether the session information is stored in Redis, Memcache or the database?

Before someone feels tempted to suggest user_logout(), that destroys the current user's session. I want the current user to be able to destroy a different user's session!

  • Nearly sure we already have a question about this. I know I have a patch in drush-extras to be able to do this, but it hasn't been committted. – mpdonadio Oct 9 '15 at 18:57
  • I googled around and searched around DA, but no luck. I'll review your patch. EDIT: Your patch unfortunately only handles the the database case. We were hoping to use memcache given the large number of users / sessions! – BrianV Oct 9 '15 at 19:00
  • 1
    I believe blocking/unblocking the user has the same effect (except they'll probably get an e-mail notification of the unblocking). You could probably use hook_mail_alter() to intercept that e-mail and suppress it. – tyler.frankenstein Oct 9 '15 at 19:01
up vote 6 down vote accepted

drupal_session_destroy_uid() sounds like a safe bet:

Ends a specific user's session(s).

The core implementation clears the database, as you'd expect, but any module that overrides session.inc, and doesn't provide a working implementation of that function, would surely be considered broken (as user_delete_multiple() and other functions need it).

So in theory you should be able to use that function regardless of the storage.

Session Proxy provides a generic replacement for Drupal's session handling that is supposed to work with various backends.
As such it also implements drupal_session_destroy_uid().

Note that the session implementation of Memcache API and Integration is considered unstable, and that the maintainer of Redis recommends the use of Session Proxy.

The problems of handling sessions consistently across various backends are outlined in issue 1260634.

In Drupal 7, We can log out a user if we have his User_ID using db_delete():

db_delete('sessions')->condition('uid', $User_ID)->execute();

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.