17

After having just registered a new account and created a profile how would I log a user in?

I have tried :

global $user;
$user = user_load($account->uid);

or

global $user;
$user = user_load(array('mail' => $_POST['email'], 'pass' => trim($_POST['password'])));

but neither work and the second results in an error about array_flip.

4 Answers 4

30

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).

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much for the answer. I tried to submit an edit but it was too few characters -- I had to pass in $login_array by reference to get this to work (so user_login_finalize(&$login_array);). Thanks again!
Hey, @Ken, I have put this code in function and have tried to call it using hook_menu(), hook_boot(), in page.tpl but it's not working for me. Either it is me showing a blank page with no message or I got login on page(created through hook_menu()) but then for other pages I get logged out automatically. Can you please help me?
@DineshSubhashPatil -- a blank page with no message (the legendary WSOD) almost certainly means there is a server error. Check your web server logs to see what's going wrong. Also you could add some error checking; in particular, before calling user_login_finalize make sure $user is a valid object. The second problem is less understandable, but could maybe be due to a problem with the PHP session? I suspect that if you track down the WSOD error, you'll solve the problem.
15

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);

1 Comment

This is a good solution but I ran into a problem with redirects. On inspecting this function, I found that it was setting the redirect property of the form. So, instead of calling user_login_submit, I used the code from the function: global $user; $user = user_load($form_state['uid']); $form_state['redirect'] = 'welcome'; user_login_finalize($form_state);
10

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.

1 Comment

Nice, clean solution.
0
/**   
*  Drupal 7 Programmatically user Login   
*/

    function hook_menu(){
      $itmes['user/form'] = array(
       'title' => t('Example Form'),
       'description' => 'Drupal Example Form',
       'page callback' => 'drupal_get_form',
       'page arguments' => array('example_form'),
       'access callback' => TRUE,
       'type' => MENU_LOCAL_TASK,
    );
      return $itmes;
   }

   function otp_login_form($form, &$form_state){
    $form['name'] = array(
     '#type' => 'textfield',
     '#title' => t('Username'),
     '#description' => t('Enter your @site_name username.',   
            array('@site_name'=> variable_get('site_name'))),
     '#required' => TRUE,
     '#size' => 60,
     '#maxlength' => 60,
     '#weight' => 2,
    );
    $form['password'] = array(
     '#type' => 'password',
     '#title' => t('Password'),
     '#description' => t('Enter the password that accompanies your  username.'),
     '#required' => TRUE,
     '#size' => 60,
     '#maxlength' => 60,
     '#weight' => 3,
    );
    $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Login'),
     '#weight' => 4,
    );

    return $form;
  }

  function otp_login_form_submit($form, &$form_state){
     if(user_authenticate($form_state['values']['name'], $form_state['values']['password'])) {
     $user_obj = user_load_by_name($form_state['values']['name']);
     $form_state['uid'] = $user_obj->uid;      
     user_login_submit($form,$form_state);
     return true;
   }
   else {
     form_set_error('name', t('Sorry, unrecognized username or password.')); 
     watchdog('user', 'Login attempt by unregistered user %user.', array('%user' => $form_state['values']['name']));

   }
 }

2 Comments

Would you like to augment your code-only answer with some explanation? That would reduce the misconception that StackOverflow is a free code-writing service.
Yes, please explain, what you did in a short sentence. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.