0

Here's what I am doing:

global $user;

if (!user_is_logged_in()) {
  $user = user_load(31);
  user_login_finalize();
  echo $user->uid;
}

When a user is not logged in - we have to log in him as user with id 31. I have placed this code at top of page.tpl.php.

I am noticing some strange behavior. If I visit the homepage (http://ggames.kz/), at the top I can see the id 31, that's correct. However, if I visit the user page (http://ggames.kz/user), it shows that I am not logged in. If I refresh the browser or visit another pages, I am logged in. I can't figure out why it won't authenticate user from the first page load?

2

Template files are not the proper place for your code, since at this level the headers are (probably) already sent. That's why the session cannot be saved on the client browser.

You'd better implement hook_init() in a custom module

function YOURMODULE_init() {
  if (!user_is_logged_in()) {
    global $user;
    $user = user_load(31);
    user_login_finalize();
  }
}

If I refresh the browser or visit another pages, I am logged in.

You are seeing the correct user ID on your debug output, just because you are printing the user id which you have loaded just 2 lines before. It doesn't mean that the user is successfully logged in.

3
  • call to undefined function user_is_logged_in() now when i am using hook_boot() – Alexander Kim Feb 1 '16 at 5:26
  • 1
    Used hook_init() instead and it did the job :) thanks – Alexander Kim Feb 1 '16 at 5:42
  • I've updated the answer – Елин Й. Feb 1 '16 at 6:40
1

The correct code to impersonate another user is the following.

global $user;
drupal_save_session(FALSE);
$user = user_load(31);

As said in Safely Impersonating Another User, this code is also safer, since the session will not be saved.

If you need to change back the user after doing something, then the code should be the following one.

global $user;
$original_user = $user;
$old_state = drupal_save_session();
drupal_save_session(FALSE);
$user = user_load(31);

// Your code here

$user = $original_user;
drupal_save_session($old_state);

As side note, changing the user account for the current user should not be something done in a template file. This type of code is expected to be executed in a module, in one of the hooks Drupal makes available, such as hook_init().

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.