X
    Categories: JqueryPHP

How to find user online status in php

How to find user online status in php

When we are working with the web based application or web based chat application it is very important to know the users online status. This can be easily implemente by using jquery or javascript and php.

Below I have given the simple example which is written by jquery, php and mysql.

My table name is ” users “, I want to store the online users into the tables to check the avaliable user staus.

How to update the user status in database?

The jquery code

<script>setInterval("update()", 5000); // Update every 5 seconds 

function update() 
{ 
$.post("update.php"); // Sends request to update.php each and every 5 seconds
} 
</script>

 The update.php [ PHP code ]

<?php session_start(); 
if ($_SESSION["userid"]) 
{

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

?>

The above code will store the user id who are all logged into the website. Thats all for storing logged users in website.

How to list the user online status from database ?

Now lets retrieve the list of users who are “online.” from database


Jqury code

<script>
setInterval("getList()", 5000) // Get users-online every 5 seconds 
function getList() 
{ 
$.post("getList.php", function(list) 
{ $("listBox").html(list); }); 
}// This function requests a bit of HTML form the server every 5 seconds.

</script>

 The getList.php [ PHP code ]

<?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; 
?>

 

 

Marimuthu:

View Comments