9

I know that in Drupal 7 I could reset the user #1 password via code.

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once DRUPAL_ROOT . '/includes/password.inc';
$newhash = user_hash_password('newpass');
$updatepass = db_update('users') 
  ->fields(array('pass' => $newhash))
  ->condition('uid', '1', '=')
  ->execute();

(user_hash_password() doesn't exist anymore in Drupal 8.)

Alternatively, I could use the following code.

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once DRUPAL_ROOT . '/includes/password.inc';
$edit['pass'] = 'newpass';
$account= user_load(1);
user_save($account, $edit);

What is the equivalent code for Drupal 8? What API should I use for this purpose?

12

It's easier these days:

$account = \Drupal::entityTypeManager()->getStorage('user')->load(1);
$account->setPassword('new password');
$account->save();
  • as always very good and clear solution, tnx Master Clive – Yusef Feb 16 '16 at 23:05
2

Alternately, since you seem to be running this as a standalone script, there is a Drush (9.x) command

drush user:password admin mynewpassword

For Drush 8.x and earlier::

drush user-password admin --password=newpass

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.