How does drupal set user cookie
The following code, let's login any user programmatically.


Not exactly; it sets the current global user object to an instance of a user, but it doesn't log the account in or touch the session. Many things that happen in that request that rely on the global user object will behave the same as if the account was logged in, but it won't be, and they won't have a session tied to the account (not yet anyway).

Cookies are added at the end of the request, in drupal_session_commit:

if (!drupal_session_started()) {
  drupal_session_start();
  if ($is_https &amp;&amp; variable_get('https', FALSE)) {
    $insecure_session_name = substr(session_name(), 1);
    $params = session_get_cookie_params();
    $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
    setcookie($insecure_session_name, $_COOKIE[$insecure_session_name], $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);
  }
}


As a by-product of the way Drupal initialises sessions (lazily in an exit hook), if the call to $user = user_load(&lt;any_uid&gt;); happens before the first session has been initialised, the session will be initialised for that user and they will appear "logged in" for their next request, even if the user_load line doesn't execute.

But, hook_user_login won't have been invoked, the last login column in the user table won't be updated, and so on. It's not a full-on "login", just initialising the session for a particular user.

Incidentally, if you call $user = user_load(&lt;any_uid&gt;); when a session already exists for another user, the session for the next request will still be for that other user. It won't be overridden with a session for &lt;any_uid&gt;.