drupal 7 programmatically log user in drupal 7 programmatically log user in php php

drupal 7 programmatically log user in


I'm going to answer this for future reference, because the third answer above is wrong, and the first answer will work but is unnecessary (it replicates the experience of the user submitting the login form, calling all validators etc, and presumably you have already done that validation or you wouldn't be trying to log the user in directly.

This will work as expected, assuming you have $username and $password from your own form or function, and you know the user is not logged in:

if ($uid = user_authenticate($username, $password)) {  global $user;  $user = user_load($uid);  $login_array = array ('name' => $username);  user_login_finalize($login_array);}

First you validate the username and password you have. If you get back a non-zero UID, the authentication succeeded. You create an array that provides the one possibly necessary piece of information that was in the original login form, and pass it to user_login_finalize(), which does all the rest (not just regenerating the session, but also recording the login properly, and calling login hooks).


Drupal does it using user_login_finalize from user_login_submit, you can invoke the same thing yourself with this code:

$form_state['uid'] = $account->uid;user_login_submit(array(), $form_state);


You can login programmatically in D7 using the following code.

global $user;$user = user_load($uid);drupal_session_regenerate();

That should log in the user with the given user id.