Add new users programatically if none exist

Last modified: August 28, 2009 - 20:45

This snippet can be posted directly into the "execute php" block that can be enabled once the devel module is installed. (Make sure that you make the block only visible to site administrators!)

This is useful if you have multiple sites that share the same users and you find yourself adding the same users again and again. Instead, fill this snippet out with their information for your users to be added, and execute this snippet. First, the snippet checks the usernames provided against those that already exist. So if you've already got a user that exists with the same username, the script will not add that user. The passwords are in plain text, and get hashed once they go into the database.

<?php

//fill out these values for the user you want to add
$new_users[0] = array(
'name' => 'login_name_here',
'pass' => 'password_here',
'mail' => 'email_here',
'access' => '0',
'status' => 0,
);

//fill out this user for the next user you wish to add.  To add more than two, cut and paste this block, making sure to add one number to the variable that immediately follows, $new_users.  For instance, the next would be $new_users[2] = arra.... you get the picture.
$new_users[1] = array(
'name' => '2nd-login_name_here',
'pass' => '2nd-password_here',
'mail' => '2nd-email_here',
'access' => '0',
'status' => 0,
);


foreach(
$new_users as $key => $value ){
$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query( $sql, $new_users[$key]['name'] );
$data = db_result( $result );
print_r($data);
if ( !
$data ) {
user_save( NULL, $new_users[$key], NULL );

}
}

?>

 
 

Drupal is a registered trademark of Dries Buytaert.