PHP MySQL Online Users Script

Track online users with PHP and MySQL in 2025. Step-by-step guide for analytics.

PHP MySQL Online Users Script

Have you ever seen websites that show something like "Users Online: 15"? This small feature makes your website look active and can build trust with new visitors.

In this tutorial, we will learn how to create a real-time online users counter using PHP and MySQL. We will start with a simple version and then make it secure, production-ready, and optimized.


🔹 What We Will Build

  • Track which users are currently online using sessions.
  • Show the total number of online users on the frontend.
  • Automatically remove users who are inactive for a set time (like 5 minutes).
  • Make the script secure with prepared statements.

 

🔹 Step 1: Create the MySQL Table

First, we need a table to store session IDs and last activity time for each visitor.

CREATE TABLE online_users (
  session_id CHAR(128) NOT NULL PRIMARY KEY,
  last_activity INT(11) NOT NULL
);
  • session_id — stores the unique PHP session ID for each user.
  • last_activity — stores the last active time in Unix timestamp.

 

🔹 Step 2: PHP Script to Track Online Users

Create a file called online_users.php. This script will:

  1. Start a session and get the current session ID.
  2. Insert or update the user's last active time.
  3. Remove old sessions (inactive users).
  4. Display the total number of online users.
<?php
session_start();

// 1. Database connection (Production-ready)
$host = "localhost";      // Database host
$user = "root";           // Database user
$pass = "password";       // Database password
$dbname = "test";         // Database name

$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}

// 2. Configurable session timeout (in seconds)
$timeout = 300; // 5 minutes

// 3. Get current session ID and timestamp
$session_id = session_id();
$current_time = time();
$expire_time = $current_time - $timeout;

// 4. Insert or update current session
$stmt = $conn->prepare("INSERT INTO online_users (session_id, last_activity)
                        VALUES (?, ?)
                        ON DUPLICATE KEY UPDATE last_activity = ?");
$stmt->bind_param("sii", $session_id, $current_time, $current_time);
$stmt->execute();

// 5. Delete old sessions (inactive users)
$stmt = $conn->prepare("DELETE FROM online_users WHERE last_activity < ?");
$stmt->bind_param("i", $expire_time);
$stmt->execute();

// 6. Count online users
$result = $conn->query("SELECT COUNT(*) AS total_online FROM online_users");
$row = $result->fetch_assoc();
$total_online = $row['total_online'];

// 7. Display result on frontend
echo "<div class='highlight'><b>Users Online: </b>" . $total_online . "</div>";

$conn->close();
?>

 

📖 Recommended: PHP Visitor Counter Script

Build a PHP visitor counter script in 2025. Easy step-by-step guide for analytics.

 

🔹 Step 3: How This Script Works

1. Sessions

Every visitor gets a unique session ID. We use this ID to track if the user is online or has already visited.

2. Updating Last Activity

Each time the user loads a page, we update their last_activity timestamp. If they are already in the table, we just update the time.

3. Removing Inactive Users

We define a timeout (like 5 minutes). If a user is inactive for longer than that, we remove their session from the table.

4. Counting Online Users

We just run a simple COUNT(*) query on our table to get the total online users.

 

🔹 Step 4: Frontend Display

Include online_users.php where you want to show the counter:

<?php include 'online_users.php'; ?>

This will show something like:

Users Online: 5

 

🔹 Step 5: Real-World Scenarios

  • ✅ If 2 users open the website at the same time, both will appear as online.
  • ✅ If a user closes the browser, they will be removed after the timeout (e.g., 5 min).
  • ✅ If the user refreshes the page, their last active time updates automatically.

 

🔹 Security and Best Practices

  • Prepared statements are used to prevent SQL Injection.
  • ✅ Session IDs are unique and stored safely, no personal info is saved.
  • COUNT(*) is used instead of SELECT * for faster performance.
  • ✅ The timeout value is configurable so you can set 1 minute, 10 minutes, etc.

 

🔹 Scaling for High-Traffic Websites

For very busy websites with thousands of users:

  • Use InnoDB with proper indexing on session_id and last_activity.
  • Reduce DELETE frequency by using a cron job to clear old sessions every few minutes.
  • Cache the online user count using Redis or Memcached to reduce database load.

 

🎯 Conclusion

With this script, you now have a secure, production-ready online users counter in PHP and MySQL. It can handle small websites easily, and with a few optimizations, it can scale for larger traffic too.

Try opening your site in multiple browsers or devices — you will see the number update in real-time!

0 Comments
Leave a Comment