top_menu

Tuesday, 3 January 2012

How to track online status of a user in website

.

I received many requests from my users asking for How to detect whether a user is online.

I found out a very simple solution using jQuery or Javascript which i've explained bellow. Please feel free to comment if you come across any issue.

track online users using jquery



The jquery part to update the user status in database
<script>setInterval("update()", 10000); // Update every 10 seconds 

function update() 
{ 
$.post("update.php"); // Sends request to update.php 
} 
</script>

The update.php file which contains the php code to update database
<?php session_start(); 
if ($_SESSION["userid"]) 
{

mysql_query("UPDATE users SET lastActiveTime = NOW() WHERE userid = 
$_SESSION['userid']") or die(mysql_error());
}

?>
This all assumes that you store your userid as a session-variable when users login to your website. Thats all about the online user status storage part.

Now lets retrieve the list of users who are "online." from database
setInterval("getList()", 10000) // Get users-online every 10 seconds 
function getList() 
{ 
$.post("getList.php", function(list) 
{ $("listBox").html(list); }); 
} 
This function requests a bit of HTML form the server every 10 seconds.

The getList.php page would look like this
<?php 
session_start(); 
if (!$_SESSION["userid"]) die; // Don't give the list to anybody not logged in 
$users = mysql_query("select username,lastActiveTime from users where lastActiveTime > NOW()-60") or die(mysql_error());
$output = "<ul>"; 
while($row=mysql_fetch_array($query))
{
$output .= "<li>".$row["userName"]."</li>"; 
} 
$output .= "</ul>"; 
print $output; 
?>

That would output the list of users who are online.