Online Users script using PHP and MySQL

, , Leave a comment

While surfing internet you may have seen many websites which displays the number of online users. Displaying number of online users may create good image on the new visitor of your website if you have decent visitors.

So how this can be implemented ? In this post we are going to learn how to make such script using PHP and MySQL. But before reading  this tutorial further, if you haven’t read previous post then please have a look at Visitors Counter Script in PHP to clear some basic concepts used in this tutorial.

This script is very simple to understand and implement.First of all create one table called “online_users” by running the below SQL .

Step: 1 Create table : “online_users”

CREATE TABLE `online_users` (
`session` char(100) NOT NULL default '',
`time` int(11) NOT NULL default '0'

Now create one file called “online_users.php” and copy the below code.

Step:2 Create file : online_users.php

$session = session_id();
$time = time();
$time_check = $time-300; //We Have Set Time 5 Minutes

$host = "localhost"; // your Host name
$username = "root"; // your Mysql username
$password = ""; // your Mysql password
$db_name = "test"; // your Database name
$tbl_name = "online_users"; // Table name

mysql_connect("$host", "$username", "$password")or die("could notconnect toserver.");
mysql_select_db("$db_name")or die("cannot select DB");

$sql = "SELECT * FROM $tbl_name WHERE session='$session'"; $result=mysql_query($sql);
$count = mysql_num_rows($result);

//If count is 0 , then enter the values
$sql1 = "INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')"; 
$result1 = mysql_query($sql1);

// else update the values
else {
$sql2 = "UPDATE $tbl_name SET time='$time' WHERE session = '$session'"; 
$result2 = mysql_query($sql2);

$sql3 = "SELECT * FROM $tbl_name";
$result3 = mysql_query($sql3);
$count_user_online = mysql_num_rows($result3);
echo "<b>Users Online : </b> $count_user_online ";

// after 5 minutes, session will be deleted
$sql4 = "DELETE FROM $tbl_name WHERE time<$time_check"; 
$result4 = mysql_query($sql4);

//To see the result run this script in multiple browser.

Script Logic 

(1) Database connection
– Simply provide the your database credentials to connect with your database.

(2) Session
– We are storing one session id in database so for each visit records will be inserted/updated and further operations will be performed based on the records received using this session id.

(3) Time

– We are deleting the session after 5 minutes , so that we can have (close to) correct number of online users.

That’s it.! We have made very simple online user counter script using PHP and MySQL. You can easily implement this logic in any PHP framework.