Ketan Patel    07-Jul-2013

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'
)

 

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.

About Ketan Patel

A Web Developer having 7+ years of experience in web development. Worked with Laravel-Lumen, CakePHP, CodeIgniter, Opencart to make sites for startup companies and small businesses. Apart from blogging, he likes to read Novels, Listening music and Net surfing.