Set users password in code? I would like to be able to change a users password in code.

Since user_load returns an object, and user_save wants an array, this is non-trivial.

I assume someone has figured out a quick and easy way to do it.



My current solution looks like:

db_update('users')
  -&gt;fields(array('pass' =&gt; user_hash_password('some_password')))
  -&gt;condition('uid', 1)
  -&gt;execute();


But I don't like that this bypasses most hooks.
You just need to call user_save() using code similar to the following one.

$edit['pass'] = 'New password';
user_save($account, $edit);


$account contains the user object for the user account to alter. I get you load it using user_load(), but it could also be the user object for the currently logged in user. In the latter case, Drupal will regenerate the session using the following code (part of user_save()).

  // If the password changed, delete all open sessions and recreate
  // the current one.
  if ($account-&gt;pass != $account-&gt;original-&gt;pass) {
    drupal_session_destroy_uid($account-&gt;uid);
    if ($account-&gt;uid == $GLOBALS['user']-&gt;uid) {
      drupal_session_regenerate();
    }
  }


The password in $edit['pass'] is the plain password. user_save() will replace it with its hash using the following code (at the beginning of the function).

if (!empty($edit['pass'])) {
  // Allow alternate password hashing schemes.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  $edit['pass'] = user_hash_password(trim($edit['pass']));
  // Abort if the hashing failed and returned FALSE.
  if (!$edit['pass']) {
    return FALSE;
  }
}


As alternative, you could use drupal_submit_form().

$form_state = array();
$form_state['user'] = $account;
$form_state['values']['pass']['pass1'] = 'New password';
$form_state['values']['pass']['pass2'] = 'New password';
$form_state['values']['op'] = t('Save');
drupal_form_submit('user_profile_form', $form_state);


In this way, if you have any module that, for example, validates the password, its code would be executed, and you would get any error code from form_get_errors().