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.– BerdirCommented Apr 11, 2011 at 1:24
-
1There 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.– iStrykerCommented Dec 22, 2014 at 14:19
Add a comment
|
1 Answer
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 withuser_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.– GregCommented 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).– iStrykerCommented Dec 22, 2014 at 14:21
-