Safely Impersonating Another User
Last modified: June 2, 2009 - 03:47
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 switch local 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() as follows:
<?php
global $user;
$original_user = $user;
session_save_session(FALSE);
$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)
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
session_save_session(TRUE);
// From here on the $user is back to normal so it's OK for the session to be saved
?>