21 Feb.2018

Drupal 10: How to create a user/administrator programmatically

Site's administrators

Running forward, I say, try to use drush, where possible. A similar operation can be performed more quickly:

drush user-create username;
drush user-password username --password="correct horse battery staple";
drush user-add-role "administrator" username;

Actually, you can also use drush user-login, without a user specified the command provides one-time login link for admin (uid=1), however, in some case, if you available to the access to the site only by using FTP or a server hasn't drush, this example can be very helpful.

Here is a very quick and simple example of how to create a user/administrator programmatically on any Drupal 8 website. This tweak is very useful when the client has provided a site for support but forgot or did not have the opportunity to create an admin account for you.

This code you can temporarily place, for example, to your theme at THEMENAME.theme and load any page of the site once. After you should remove this code.

File
THEMENAME.theme
use Drupal\user\Entity\User;
 
// Create user object.
$user = User::create();
 
// Mandatory settings.
$user->setUsername('username'); // This username must be unique and accept only [a-Z,0-9, - _ @].
$user->setPassword('password');
$user->setEmail('email');
$user->addRole('administrator'); // E.g: authenticated.
$user->enforceIsNew();
$user->activate();
$user->save();

Don't forget to remove the code ;)

The similar code for Drupal version 7 here.

Have a nice time :-)

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.