开发者

Checking whether a user already exists in drupal

When a user enters his login information and hits submit, i want to check if the user already exists or not. So, i have the following two questions 1. Which hook is needed to be implemented 开发者_高级运维, for the case when user hits the submit button on the login form. I need the username entered by the user. 2. How to check if a user already exists in drupal or not programmatically ?

Some sample code would be really appreciated. Please help.

Thank You.


Drupal 7 provides a function to get a user object by name :

$user = user_load_by_name($name);
if(!$user){
    // User doesn't exist
} 
else {
    // User exists
}

http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load_by_name/7


This can be done with hook_form_alter:

function module_(&$form, &$form_state, $form_id) {
  $user_login_forms = array('user_login', 'user_login_block');
  if (in_array($form_id, $user_login_forms)) {
    $form['#validate'][] = 'my_validate_function';
  }
}

function my_validate_function(&$form, &$form_state) {
  $name = $form_state['values']['name'];
  // Drupal 6:
  if (!db_result(db_query("SELECT COUNT(*) FROM {users} WHERE name = '%s';", $name))) {
    // User doesn't exist
  }
  // Drupal 7:
  if (!db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' => $name))->fetchField()) {
    // User doesn't exist
   }
}

It's better to query the DB directly in this case than than using user_load as it hooks into other modules as well.


In Drupal 7, substitute for this in the validation function:

if (!db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' => $name))->fetchField()) {
  // User doesn't exist
}


I realize this is almost 2 years old, but user_authenticate does this nicely.

$existing_user = user_authenticate($name,$password);
if($existing_user)
  // user exists
else
  // user doesn't exist

Hope this helps someone else.


You can try to look on these 2 modules for inspiration: friendly_register and username_check.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜