Detecting A Drupal Users First Login

Being fairly new to Drupal, I was interested to know whether it had anything built in that let you know, or detect, when a user was logging in for the first time e.g. to show them a welcome message.

As far as I know, there’s no method in the API to detect this. However, after checking the global $user object's properties to see what we had to play with, it turns out it wasn't all that tricky:

  • the $global user contains 3 timestamp properties: created, access and login
  • when a user logs in for the first time, all 3 of these timestamps are equal

This means we can check whether a user is logging in for the first time with something like this:

function is_first_time_login($user) {
  return ($user->created == $user->login) && 
         ($user->login == $user->access);
}

Now we can call that function where we need to in our elsewhere in our code. For example:

function foo() {
  global $user;
  ...
  if (is_first_time_login($user)) {
    drupal_set_message(WELCOME_MSG);
  }
  ...	
}

So far, this approach seems to be working quite well :)

Posted in web by Ian at August 5th, 2010.
Tags: ,

2 Responses to “Detecting A Drupal Users First Login”

  1. ruinze says:

    good day my friend, i just want to clarify something…created timestamp will only be equal to login and access if the user logs in right after registration, example if a particular user registers on the current date the values will be; created = current time : login = 0 : access = 0 , and if that user will login let’s say the 2nd day from current then the values would be created = original created date : login = offset + 2 days : access = offset + 2 days

  2. Ian says:

    Ah, good point – hadn’t thought of that. The site I used this on was set to log a user in straight away once they’d registered, hence the values being the same.

Leave a Reply