Programmatically log in user not working correctly
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.