Programmatically log in user not working correctly Here's what I am doing:

global $user;

if (!user_is_logged_in()) {
  $user = user_load(31);
  user_login_finalize();
  echo $user-&gt;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?
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.