Last updated November 25, 2011. Created by xamount on February 5, 2008.
Edited by joachim, axel.rutz, sanduhrs, fgm. Log in to edit this page.
Is Change Coming?
There's an issue to move this functionality into core so that developers don't have to remember the how to do this safely: #287292: Add function to impersonate a user
Impersonating Possibilities
There are many times when you may want your code to "impersonate" another user. An example of this is when a user takes an action that triggers another process. If that other process should be done as a different user then you want to impersonate that other user.
Here is some example code to impersonate another user which is unsafe:
<?php
global $user;
$original_user = $user;
$user = user_load(array('uid' => 1));
// Take your action here where you pretend to be the user with UID = 1 (typically the admin user on a site)
// NOTE: - this is the unsafe part - if your code here fails, then the user suddenly has the permissions of UID 1!
$user = $original_user;
?>The safe way to implement this is to use the function session_save_session() (D6) or drupal_save_session() (D7) as follows:
For D6:
<?php
global $user;
$original_user = $user;
$old_state = session_save_session();
session_save_session(FALSE);
$user = user_load(1);
// Take your action here where you pretend to be the user with UID = 1 (typically the admin user on a site)
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
session_save_session($old_state);
// From here on the $user is back to normal so it's OK for the session to be saved
?>For D7:
<?php
global $user;
$original_user = $user;
$old_state = drupal_save_session(FALSE);
$user = user_load(1);
// Take your action here where you pretend to be the user with UID = 1 (typically the admin user on a site)
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
drupal_save_session($old_state);
// From here on the $user is back to normal so it's OK for the session to be saved
?>
Comments
D7 version is
D7 version is incorrect...Should be almost the same as D6:
<?php
global $user;
$original_user = $user;
$old_state = drupal_save_session();
drupal_save_session(FALSE);
$user = user_load(1);
// Take your action here where you pretend to be the user with UID = 1 (typically the admin user on a site)
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
drupal_save_session($old_state);
// From here on the $user is back to normal so it's OK for the session to be saved
?>