9

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 Apr 11 '11 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 Dec 22 '14 at 14:19
18

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();
drupal_save_session(FALSE);

// 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;
drupal_save_session($original_session_state);
  • 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 Mar 4 '11 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 Dec 22 '14 at 14:21
  • accessing and capturing the screen using drupal.org/project/phantomjs_capture as other user. Is it possible/tricky ? (DO issue drupal.org/node/2899252). – kiranking Aug 11 '17 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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