2

How can i check if user is logged in for the first time on site?

If it is, i want to show him a message...

Can someone help me?

Thank you!

3

** UPDATE **

As suggested by oknate, using hook_user_login:

function hook_user_login(&$edit, $account)
{
  if(!$account->access)
  {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}

** Original less optimal method **

You can use hook_init() in D7, and check if they have a value for last access:

function hook_init()
{
  global $user;

  $first_login = db_query('SELECT 1 FROM {users} WHERE uid = :uid AND access = 0', array(':uid' => $user->uid))->fetchField();

  if($first_login)
  {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}
  • hook_init runs on every uncached page load. I would suggest finding another way. – oknate Dec 19 '16 at 23:31
  • There are ways you can minimize it - such as adding a field to the {users} table and flagging in on first login. This would be automatically loaded with the user object for every page load, not requiring the additional query shown here. But I don't see any other way you could do it without checking on every page load. Suggestions? – Jaypan Dec 19 '16 at 23:33
  • 1
    look into hook_user_login, and the $user->access flag on the user. – oknate Dec 19 '16 at 23:34
  • That's a good suggestion. – Jaypan Dec 19 '16 at 23:35
  • then $account->access, see drupal.stackexchange.com/questions/34397/… – oknate Dec 19 '16 at 23:36
3

In both Drupal 7 and 8, there is hook_user_login, where you can can check whether the current user has accessed the site before, but the parameters are slightly different.

Drupal 7 version:

function mymodule_user_login(&$edit, $account) {
  if ($account->access == 0) {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}

Drupal 8 version:

function mymodule_user_login($account) {
  if (!$account->getLastAccessedTime()) {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}

hook_user_login in Drupal 8.

0

For D7 you can use rules to achieve the same,

Here is the sample rule,

{ "rules_first_login_test" : {
    "LABEL" : "First login test",
    "PLUGIN" : "rule",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [ { "data_is_empty" : { "data" : [ "user:last-access" ] } } ],
    "DO" : [ { "drupal_message" : { "message" : "True" } } ]
  }
}

Import this rule and modify according to your need.

You can check the more information here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.