Hey

Does anybody know how to change the password for a user programmatically?

I have taken this code from a Drupal 7 site i created once, and it does not throw any errors but if i try to log in afterwards with the username or email for the user (uid 64) and the password 'newpassword' it gives me an error saying the password is wrong. However if i try to change the value of a custom field it works fine for that, but the password does not work. Any ideas on what to do to update the password for the user?

require_once 'core/includes/password.inc';
$account = user_load(64);
$password = 'newpassword';
$account->pass = user_hash_password($password);
$account->field_phone['und'][0]['value'] = "12345678"; // This is updated
user_save($account);

 

Accepted answer

Hi fjeder,

You don't need to hash the password as this happens automatically during pre-save: UserStorageController::preSave

So use this instead:

require_once 'core/includes/password.inc';
$account = user_load(64);
$password = 'newpassword';
$account->pass = $password;
$account->field_phone['und'][0]['value'] = "12345678"; // This is updated
user_save($account);

Comments

BWPanda's picture

Hi fjeder,

You don't need to hash the password as this happens automatically during pre-save: UserStorageController::preSave

So use this instead:

require_once 'core/includes/password.inc';
$account = user_load(64);
$password = 'newpassword';
$account->pass = $password;
$account->field_phone['und'][0]['value'] = "12345678"; // This is updated
user_save($account);

Hi BWpanda

Thank you for your reply. That makes sense, and it looks like it works perfectly :)