[Drupal 7] How to programmatically change the password of a user

| | 1 min read

If you run into a Drupal 7 site with file system access and you would want to change the password of a user in the system programmatically, here is an easy way to do this.

Copy and paste the following code into a file named with a random name like 231818151.php in the webroot

define('DRUPAL_ROOT', getcwd());   
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
require_once DRUPAL_ROOT . '/includes/password.inc';

$newhash = user_hash_password('replace_this_with_new_password');
$updatepass = db_update('users')->fields(array('pass' => $newhash))->condition('uid', 'replace_this_with_your_userid', '=')->execute();
echo "Done";

Then access the file from your browser and you should be set.

Do note that leaving this file on the server is a security risk and you should remove this as soon as you are done.