Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Drupal user password programmatically?

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

like image 890
ohho Avatar asked Oct 14 '10 04:10

ohho


2 Answers

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();
    }
 }
like image 86
hussain Avatar answered Oct 13 '22 00:10

hussain


There are already many nice answers in here, but I believe I add the one which I found easy for me.

// ID of the user whose password you wish to change.
$uid = 1;

// Load the user account.
$account = user_load($uid);

// Load hashing libraries.
// You can use module_load_include() if you want to make it cleaner.
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

// Generate new password hash.
$password_hash = user_hash_password('enter-new-password-here');
if (!$password_hash) {
  // Password could not be hashed. Handle the error.
  exit('Password could not be hashed.');
}

$account->pass = $password_hash;
user_save($account);

Given everything is set up correctly, your user's password would be updated.

Note: If you have forgotten your root password, you can safely ignore the error handling, etc. Add these lines in index.php before menu_execute_active_handler(); and open any page to reset your password. Don't forget to remove the lines after you're done though!

like image 24
Jigarius Avatar answered Oct 13 '22 00:10

Jigarius