How should a module change the value of the global $user, execute its own code, and restore the original value of $user without causing the current user to be logged out if an error happens?

  • There is an old issue open about this, which adds a function that can properly handle this, even when called multiple times. See drupal.org/node/287292. Please review and test the patch there.
    – Berdir
    Commented Apr 11, 2011 at 1:24
  • 1
    There has been a Community Documentation create that has the solution to impersonate another user for Drupal 6, Drupal 7 and Drupal 8 on drupal.org: Safely Impersonating Another User.
    – iStryker
    Commented Dec 22, 2014 at 14:19

1 Answer 1


The drupal_cron_run() function gives a perfect example for exactly this, since it changes the current user to anonymous whenever cron is run, then switches back after it is done.

// Prevent session information from being saved while doing funky stuff.
$original_session_state = drupal_save_session();

// Force the current user to anonymous to ensure consistent permissions on
// funky stuff runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user(); // Or use user_load() for a non-anonymous user.

// Do funky stuff here...

// Restore the user.
$GLOBALS['user'] = $original_user;
  • Worth noting you can put the current user object away somewhere (in $GLOBALS or just in another variable for safe-keeping) and switch to any user by loading them in with user_load(). Which allows you to do some horrible things like masquerade as a specific users set up with specific permissions to perform a specific process. The principle is the same.
    – Greg
    Commented Mar 4, 2011 at 9:42
  • Only potential 1 problem with this piece of code. You should save the old session in a variable $old_session. Set the save session to false, then at the end drupal_save_session($old_session).
    – iStryker
    Commented Dec 22, 2014 at 14:21
  • Just a note for Drupal 8/9 You can use the AccountSwitcher service Commented Jan 5, 2021 at 1:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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