Drupal 7 : create user programmatically

Here is Code to create new user programmatically:

<?php
//This will generate a random password, you could set your own here
         
$password = user_password(8);
        
         
//set up the user fields
         
$fields = array(
           
'name' => $mail,
           
'mail' => $mail,
           
'pass' => $password,
           
'status' => 1,
           
'init' => $mail,
           
'field_user_first_name' =>
                array(
LANGUAGE_NONE =>
                array(
0 =>
                array(
'value' => $name))),           
           
'roles' => array(
             
DRUPAL_AUTHENTICATED_RID => 'authenticated user',
            ),
          );
         
$account = user_save('', $fields);
?>

Here is Code to update user password programmatically:

<?php
      $existingUser
= user_load($uid);
   
// update some user property
   
$existingUser->password = $pwd;
   
// save existing user
   
user_save((object) array('uid' => $uid), (array) $existingUser);
   
      
// this is login user programmitically
   
global $user;
   
$user = user_load($uid);
   
drupal_session_regenerate();
?>

Here is Entity field query sample code to filter user by email address

<?php
       $users
= array();
   
$query = new EntityFieldQuery();
   
$query->entityCondition('entity_type', 'user')
      ->
propertyCondition('mail', $email);
   
$results = $query->execute();

   
$users = user_load_multiple(array_keys($results['user']));
    if(
count($users) > 0 ) {
        foreach(
$users as $usernew) {           
            return
$usernew->id;
        }
    }
?>

Share this post

Leave a comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.