Displaying a list of users that are currently logged in

News, PHP, Tutorials

Some web applications like forum or Q&A website may benefit from the list of active users displayed somewhere on the page. In this article we’ll show how to add such functionality to PHPRunner application. ASPRunnerPro/ASPRunner.NET code to follow.

We need to remember that sometimes in web application we can not determine if user is still active or left his computer or even closed his browser. What we actually going to do is to find the list of users that performed some action on the website in last 10 minutes.

We assume that login table is named users and username field is username. We are going to add one more datetime field to the login table named lastaccess.



1. AfterAppInit event

if ($_SESSION["UserID"]!="" && $_SESSION["UserID"]!="Guest") {
	$sql = "update users set lastaccess=now() where username='".$_SESSION["UserID"]."'";
	CustomQuery($sql);
}

2. Header file. Since we plan to display this info somewhere close to the top of each page the logical place for this code is header file. In Visual Editor open Header file, switch to HTML mode and paste the following code there.

You can adjust inactivity time and number of users to display. If you have a large community you do not want to display hundreds of users. By default first 20 users will be displayed.

<?php

$minutes=10;
$dispUsers=20;
$t=date('Y-m-d H:i:s', time()-$minutes*60);
// display users who were active in last 10 minutes

$users=DBLookup("select count(*) from invusers where lastaccess > '".$t."'");
if ($users>0) {
	$sql="select * from invusers where lastaccess > '".$t."'";
	$rs=CustomQuery($sql);

	if ($data = db_fetch_array($rs)) {
		echo $users." active user(s): ".$data["username"];
	}
	$count=1;
	while ($data = db_fetch_array($rs)) {
	  if ($count<$dispUsers) {
			$count++;
			echo ", ".$data["username"];
	  }
		else {
			echo " ...";
			break;
		}
	}
}
?>

And this is how it looks in generated application.

5 thoughts on “Displaying a list of users that are currently logged in

  1. I can’t get code to work.. no errors, just doesn’t display anything. Lastaccess table being updated… hmmm

  2. got it working… it wasn’t taking into account daylights savings time, so I change 10 minutes to 70 and it worked.

Leave a Reply

Your email address will not be published. Required fields are marked *