Drupal 7: Create a user programmatically and give the administrator role

15 Feb.2017
Image
Site's administrators

Here is a very quick and simple example of how to create an administrator on any drupal 7 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.

Open your index.php and put the following code after drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);.

File
index.php
$new_user = array(
  'name' => 'USER_NAME',
  'pass' => 'USER_PASS', // Note: do not use md5 the password.
  'mail' => 'USER@MAIL',
  'status' => 1,
  'init' => 'USER@MAIL',
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    3 => 'administrator',
  ),
);
 
// The first parameter is sent blank, so a new user is created.
user_save('', $new_user);

Don't forget to remove the code ;)

A similar code for Drupal version 8 is here.