Hi All,

Just wondering if there was any module/snippet that I can use to display the last login time of a user. I looked at the tracker module, but I can't see that functionality there.

Comments

ajwwong’s picture

in case anyone knows how to do this, thanks!

if i figure it out, i'll post it here. :-)

Albert
www.ithou.org

Andreas Wolf’s picture

Hi,

the last login time is saved in user->login.

E.g. in a module you can add a field with hook_user to the user account view:

/**
 * Implementation of hook_user().
 */
function mymodule_user($type, &$edit, &$user, $category = NULL) {
  switch ($type) {
    case 'view':
      $items['Last Login'] = array(
        'title' => t('Last login'),
        'value' => format_date($user->login,'small'), 
        'class' => 'mymodule',       
      );      
      return array(t('History') => $items);
      break;
}

in a block or theme you can do a simple echo

  global $user;
  echo "Last login: ".format_date($user->login,'small');
jayakrishnan-1’s picture

It will display the current date and time and not last time the user logged in. I tried it and thats what it does

This is how i did

1. Create a table lh

create table lh(uid varchar(3),time varchar(50));

2. Enter the following line in the user_logout function in user.module file, just after the watchdog function call

$lld='"'.date("D M j G:i:s T Y").'"';
$lui='"'.$user->uid.'"';

$sql1 = 'delete from lh where uid='.$lui.';';
$args1[] = PROFILE_PUBLIC_LISTINGS;
db_query($sql1, $args1);    

$sql1 = 'insert into lh values('.$lui.','.$lld.');';
    
  $args1[] = PROFILE_PUBLIC_LISTINGS;
db_query($sql1, $args1);  

3. Used the advanced front page module and created a page for the authenticated users and put the following code. Dont forget to enable php support

<?php
  global $user;

echo "<div class=welcome>";
  echo "Hello There <b>".$user->name."</b> Welcome to CIT Alumni 1996 page";

    $sql1 = 'select * from lh where uid='.$user->uid.';';
  $args1[] = PROFILE_PUBLIC_LISTINGS;
$hc = db_query($sql1, $args1); 

    while ($hr = db_fetch_object($hc))
    {
$output ="<br><br>Last Login at :";   	
$output .=  $hr->time;    
    } 

echo $output;   
echo "</div>";
?>

Now clicking on Home link will display the users last login date and time

syngi’s picture

I also needed this, but with the help of the holy book 'Pro Drupal Development' (:p) I think I managed to do this the 'better' way. Please note that this is my first piece of Drupal code, so correct or help me anywhere it's needed.

(I don't know if it matters, but I'm using Drupal 5.5)

I developed a tiny module consisting of 4 files:
- LICENSE.txt, telling anyone that this module is distributes under GNU GENERAL PUBLIC LICENSE.
- README.txt, containing:

Remembers the login time as last_login when logging off. This makes the
display of the previous login time possible.

INSTALLATION:

1) Place this module directory in your modules folder (this will usually be
"sites/all/modules/").

2) Enable the module.

3) Use the $GLOBALS['user']->last_login to get the date and time of
the previous login

- user_last_login.info, containing:

; $Id$
name = Users's last login
description = Remembers the last login of users.
package = Core - optional
version = "$Name$"

- and user_last_login.module, containing:

// $Id$

/**
 * @file
 * Registers the last login of a user.
 */

/**
 * Implementation of hook_user()
 */
function user_last_login_user($type, &$edit, &$user, $category = NULL) {
  if ($type == 'logout') {
	$last_login = array('last_login' => $user->login);
	user_save($user, $last_login);
  }
} 

It works well for me so I believe it's a nice solution for having the last login timestamp available. Again, correct me anywhere I might be wrong or anywhere I could improve something...
Also, can I share this module (through Drupal's contributes modules repository ?) and how do I do that?

Paul

syngi’s picture

Hmm I believe my code and also the code above won't work when a user not actually logs out, but closed his browser and gets re-logged in by his cookie. Then the session where he left without logging out doesn't seem to get recored.

How Can I improve the code?

Does perhaps the load operation run before load?

syngi’s picture

Of course to use the value 'last_login' just use '$GLOBALS['user']->last_login' and format it with 'format_date'.

Muslim guy’s picture

<?php
  //Last logged in
  global $user;
  if ($user->uid>0){
   $userid = arg(1);
   //$userid = '1';

   $u = user_load(array("uid" => $userid));

   $output9 .= '<TABLE BORDER="1" CELLPADDING="1"  CELLSPACING="3" WIDTH="100%"> <TR><TD BGCOLOR="#f5f4ff"><FONT SIZE=-1>';

   $output9 .= '<FONT SIZE=-2><B>Last access:<BR> <FONT SIZE=-2>';
   $output9 .= format_date($u->access,'short');

   $output9 .= "</TD></TR></TABLE><BR>";
   $output9 .= "</FONT></B><FONT SIZE=-1>"; 
   $output9 .= '<center>';

  $output9 .=  "</center>";
  print $output9;
  }
?>


*Only works in user* and in a block. If u want to use in userprofile-tpl.php, it wont display correctly.

*If user requires verification and he never verifies it, the last access date will display weird years (like 1970) - anyway, only admin can see a non-verified user account

syngi’s picture

This code will give the current date and time of when the current page has loadded (last user action), not the previous login time.

syngi’s picture

I was after also registering the time when a user re-visits the site after he closed the browser, but turns out there is no hook for that and this seems to not make sense to people, so I stopped trying.

Meanwhile I tried to register the last login time on login insetad of logout, but this neither registered the re-visits.
Anyhow, that code is

function user_last_login_user($type, &$edit, &$user, $category = NULL) {
  if ($type == 'login') {
	// remembering the previous login time (that came out of the database)
	$last_login = $user->last_login;
	// then overwriting (the database value) for next session
	$last_login = array('last_login' => $user->login);
	user_save($user, $last_login);
	// and finally restoring the value on the $user object to use throughout this session
	$user->last_login = $last_login;
  }
}
gdesmarais’s picture

I found that the posted code for the user hook on login was not quite working. Since the last_login was updated in the db at the time of login, any time the user object was re-loaded from the db the last_login value was actually set to the login time for that session. I was looking for the login time of the previous session. I just ended up stacking the login in times one level deep. I suppose you could give the module a set of config options to keep an arbitrary depth stack of login history. Here is my simplistic (and naive) implementation - essentially popping off the stack:

function user_last_login_user($type, &$edit, &$user, $category = NULL) {
  if ($type == 'login') {
      $currentLogin = $user->login;
      $previousLogin = $user->last_login;
      $backTwo = $user->last_login_stack;

      $newPreviousLogin = array('last_login' => $backTwo);
      user_save($user, $newPreviousLogin);
      $newBackTwo = array('last_login_stack' => $currentLogin);
      user_save($user, $newBackTwo);
  }
}
victorlf’s picture

There's a better way of doing this in drupal 6. I edited the function user_authenticate_finalize(&$edit) in modules/user/user.module.
If you want to display the last time the account was used, symply add a line:

function user_authenticate_finalize(&$edit) {
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = time();
  db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);

  // Regenerate the session ID to prevent against session fixation attacks.
  sess_regenerate();
  user_module_invoke('login', $edit, $user);
  drupal_set_message('Last time the user used the website: '. format_date($user->access)); // Added line
}

I wanted to display this date so users can check if the account has been used by someone else. $user->access accomplishes this purpose. If you want to display the last login time, I found I had to use an auxiliar variable. Maybe someone can do it cleaner? This is how:

function user_authenticate_finalize(&$edit) {
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $last_login_time = $user->login; // 1st added line
  $user->login = time();
  db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);

  // Regenerate the session ID to prevent against session fixation attacks.
  sess_regenerate();
  user_module_invoke('login', $edit, $user);
  drupal_set_message('Last time the user used the website: '. format_date($last_login_time)); // 2nd added line
}
gdesmarais’s picture

I found that the posted code for the user hook on login was not quite working. Since the last_login was updated in the db at the time of login, any time the user object was re-loaded from the db the last_login value was actually set to the login time for that session. I was looking for the login time of the previous session. I just ended up stacking the login in times one level deep. I suppose you could give the module a set of config options to keep an arbitrary depth stack of login history. Here is my simplistic (and naive) implementation - essentially popping off the stack:

function user_last_login_user($type, &$edit, &$user, $category = NULL) {
if ($type == 'login') {
$currentLogin = $user->login;
$previousLogin = $user->last_login;
$backTwo = $user->last_login_stack;

$newPreviousLogin = array('last_login' => $backTwo);
user_save($user, $newPreviousLogin);
$newBackTwo = array('last_login_stack' => $currentLogin);
user_save($user, $newBackTwo);
}
}

agungsuyono’s picture

In drupal 6, in table users, there's a field access. Probably it can be utilized to get who is the last login...

golubovicm’s picture

In "users" table there is field called 'login' - should that be it?

madmanmax’s picture

The solution I used: keep track of the last two log-in timestamps (the current and the previous one).

/**
 * Implementation of hook_user()
 */
function your_module_user($op, &$edit, &$account, $category = NULL) {
  switch($op) {

    // Successful login
    case 'load':
      // If it's less than two it means we don't have a previous login timtestamp yet.
      $account->custom_last_login = sizeof($account->custom_login_history) < 2 
        ? NULL 
        : array_pop($account->custom_login_history); 
      break;

    case 'login':
      // If it's the first time, we don't have a history
      $login_history = is_array($account->custom_login_history) 
        ? $account->custom_login_history 
        : array();

      // Get rid of the old value.
      if (sizeof($login_history) == 2) {
        array_pop($login_history);
      }

      // Add to the history the current login timestamp.
      array_unshift($login_history, $account->login);

      user_save($account, array('custom_login_history' => $login_history));
      break;
  }
}

Then in your template you just use $user->custom_last_login. If it's empty it means we don't have the previous timestamp yet, will be available after the next login.

w01f’s picture

Hi, I'm looking for a way to sort a views by the author's last login - so that the most recently logged in authors' nodes would appear first. Any idea how this might be possible?

cl2000’s picture

There is a drupal module called login security, which has a checkbox that you can select, that says, display users last login session time, when the user has logged in.