Online Users Script Using PHP And MySQL

You may have come across websites that display the number of online users, which can make a good impression on new visitors if you have a decent amount of traffic.

This post will show you how to create such a script using PHP and MySQL. However, if you haven't already, it's recommended that you first read the "Visitors Counter Script in PHP" tutorial to gain a better understanding of the 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'
)

 

Step:2 Create file : online_users.php

<?php
session_start();
$session    = session_id();
$time       = time();
$time_check = $time-300;     //We Have Set Time 5 Minutes
$tbl_name   = "online_users";


$conn = new mysqli("localhost","root","password","test");
// Check connection
if ($conn->connect_errno) {
  echo "Failed to connect to MySQL: " . $conn->connect_error;
  exit();
}

$sql    = "SELECT * FROM $tbl_name WHERE session='$session'";
$result = mysqli_query($conn, $sql);
$count  = mysqli_num_rows($result); 

//If count is 0 , then enter the values
if ($count == "0") { 
  $sql1    = "INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')"; 
  $result1 = mysqli_query($conn, $sql1);
} else {
  $sql2    = "UPDATE $tbl_name SET time='$time' WHERE session = '$session'"; 
  $result2 = mysqli_query($conn, $sql2); 
}

$sql3              = "SELECT * FROM $tbl_name";
$result3           = mysqli_query($conn, $sql3); 
$count_user_online = mysqli_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 = mysqli_query($conn, $sql4); 

//To see the result run this script in multiple browser. 
mysqli_close($conn);
?>

 

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.

Ketan Patel

As a backend and ecommerce developer, I have extensive experience in implementing robust and scalable solutions for ecommerce websites and applications. I have a deep understanding of server-side technologies and have worked with various programming languages. I have experience in integrating with payment gateways, and other third-party services.