How to change Drupal user password programmatically?

ohho picture ohho · Oct 14, 2010 · Viewed 10.1k times · Source

We are going to deploy a Drupal site inside company's intranet. There is a requirement for user to reset password. We have a centralized password reset mechanism (for single sign on):

  • user submits a password change request in system
  • the request is sent to a password server
  • the password server will reset the user's password in all systems with a new password
  • the password server will send the new password to user's mobile phone via sms

Now we are going to add the Drupal site to all systems. Please suggest a way to change the Drupal's logon password by an external program (assume the system can run script on the Drupal host and edit Drupal MySQL database).

Answer

hussain picture hussain · Aug 17, 2014

For Drupal 7 -- Hope this custom function code resolves change password for anonymous user.

function password_reset(){
    global $user;
    $hashthepass = 'password'; /* Your password value*/
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
    $hashthepass = user_hash_password(trim($hashthepass));
    // Abort if the hashing failed and returned FALSE.
    if (!$hashthepass) {
      return FALSE;
    }
    else {
      db_update('users')
        ->fields(array(
          'pass' => $hashthepass
        ))
        ->condition('uid', $user->uid)       
        ->execute();
    }
 }