Show realtime website users counter – Node JS

In this article, we are going to show you how you can get realtime website users counter using Node JS. Paste the following code in page where you want to display the counter:

HTML

<div class="row">
	<div id="countdown">
		<div id='tiles'>
			<span>0</span>
			<span>0</span>
			<span>0</span>
			<span>0</span>
		</div>

		<div class="labels">
			<li>Registered users</li>
		</div>
	</div>
</div>

CSS

#countdown{
    width: 465px;
    height: 170px;
    text-align: center;
    background: #222;
    background-image: -webkit-linear-gradient(top, #222, #333, #333, #222); 
    background-image:    -moz-linear-gradient(top, #222, #333, #333, #222);
    background-image:     -ms-linear-gradient(top, #222, #333, #333, #222);
    background-image:      -o-linear-gradient(top, #222, #333, #333, #222);
    border: 1px solid #111;
    border-radius: 5px;
    box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.6);
    margin: auto;
    padding: 24px 0;
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
}

#countdown:before{
    content:"";
    width: 8px;
    height: 65px;
    background: #444;
    background-image: -webkit-linear-gradient(top, #555, #444, #444, #555); 
    background-image:    -moz-linear-gradient(top, #555, #444, #444, #555);
    background-image:     -ms-linear-gradient(top, #555, #444, #444, #555);
    background-image:      -o-linear-gradient(top, #555, #444, #444, #555);
    border: 1px solid #111;
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
    display: block;
    position: absolute;
    top: 48px; left: -10px;
}

#countdown:after{
    content:"";
    width: 8px;
    height: 65px;
    background: #444;
    background-image: -webkit-linear-gradient(top, #555, #444, #444, #555); 
    background-image:    -moz-linear-gradient(top, #555, #444, #444, #555);
    background-image:     -ms-linear-gradient(top, #555, #444, #444, #555);
    background-image:      -o-linear-gradient(top, #555, #444, #444, #555);
    border: 1px solid #111;
    border-top-right-radius: 6px;
    border-bottom-right-radius: 6px;
    display: block;
    position: absolute;
    top: 48px; right: -10px;
}

#countdown #tiles{
    position: relative;
    z-index: 1;
}

#countdown #tiles > span{
    width: 92px;
    max-width: 92px;
    font: bold 48px 'Droid Sans', Arial, sans-serif;
    text-align: center;
    color: #111;
    background-color: #ddd;
    background-image: -webkit-linear-gradient(top, #bbb, #eee); 
    background-image:    -moz-linear-gradient(top, #bbb, #eee);
    background-image:     -ms-linear-gradient(top, #bbb, #eee);
    background-image:      -o-linear-gradient(top, #bbb, #eee);
    border-top: 1px solid #fff;
    border-radius: 3px;
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.7);
    margin: 0 7px;
    padding: 18px 0;
    display: inline-block;
    position: relative;
}

#countdown #tiles > span:before{
    content:"";
    width: 100%;
    height: 13px;
    background: #111;
    display: block;
    padding: 0 3px;
    position: absolute;
    top: 41%; left: -3px;
    z-index: -1;
}

#countdown #tiles > span:after{
    content:"";
    width: 100%;
    height: 1px;
    background: #eee;
    border-top: 1px solid #333;
    display: block;
    position: absolute;
    top: 48%; left: 0;
}

#countdown .labels{
    width: 100%;
    height: 25px;
    text-align: center;
    position: absolute;
    bottom: 8px;
}

#countdown .labels li{
    /*width: 102px;*/
    font: bold 15px 'Droid Sans', Arial, sans-serif;
    color: #f47321;
    text-shadow: 1px 1px 0px #000;
    text-align: center;
    text-transform: uppercase;
    display: inline-block;
}

Display currently registered users

Paste the following code before the counter is displayed:

<?php
	$conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");
	$result = mysqli_query($conn, "SELECT COUNT(*) AS total_users FROM users");
	$row = mysqli_fetch_object($result);
	$total_users = $row->total_users;
	$total_users = substr("0000" . $total_users, -4);
?>

This will return the number of users in 4 digit format. For example, if your website has 275 users then substr(“0000” . $total_users, -4):

  • “0000” will print 4 zeroes.
  • $total_users will append 275, thus makes 0000275.
  • -4 will pick the last 4 characters, thus becomes 0275.

We need to display each character in 1 block, so we will loop through length of this digit and display single character in each iteration.

<?php for ($a = 0; $a < strlen($total_users); $a++) { ?>
	<span><?php echo $total_users[$a]; ?></span>
<?php } ?>

Setup Node JS

Download and install Node JS from here. After installation, create a new folder for Node JS and create a new file named “index.js”. Open command prompt in this folder and run the following command:

npm init

This will initialize the directory. Then you need to install 3 modules for this, you can install all 3 of them from single command:

npm install express http socket.io

When all above modules installs, open your index.js file and paste the following code in it:

var express = require("express");
var app = express();
var http = require("http").createServer(app);
var socketIO = require("socket.io")(http);

http.listen(3000, function () {
	socketIO.on("connection", function (socket) {
		socket.on("new_user", function () {
			socket.broadcast.emit("new_user");
		});
	});
});

And run the command in your command prompt:

node index.js

This will start the server and keep listen for incoming events for “new_user” event. As soon that event is received, it broadcast that event to all other connected clients. Broadcast means to send the event to all users except the one who sends it.

Send event when new user gets registered

So the server is listening for incoming events and sending to all other connected clients. Now we need to send event whenever new user gets registered. On registration form, attach an onsubmit event and call a function to send event to server. Make sure the function must returns true otherwise your action attribute will not work.

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>

<form action="your_action_page" onsubmit="return sendEvent();" method="POST">

JS

function sendEvent() {
	var socketIO = io("http://localhost:3000/");
	socketIO.emit("new_user");
	return true;
}

Receive event on counter page

So an event is sent from registration page to server, and sends it to all other connected clients. But there isn’t any client to receive it yet, so we will be listening to this event on our page where we want to display the counter. In this case, we are displaying counter on home page.

When the event is received we will increment the current users number and display it in 4 digit format, like we did for PHP. In order to increment the current number, we first must have the old number, so we have created an hidden field for it.

<input type="hidden" id="total_users" value="<?php echo $row->total_users; ?>">

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>

JS

var socketIO = io("http://localhost:3000/");
socketIO.on("new_user", function () {
	var total_users = document.getElementById("total_users").value;
	total_users++;

	var totalUsers_Str = total_users + "";
	totalUsers_Str = totalUsers_Str.padStart(4, "0");

	var html = "";
	for (var a = 0; a < totalUsers_Str.length; a++) {
		html += "<span>" + totalUsers_Str[a] + "</span>";
	}

	document.getElementById("tiles").innerHTML = html;
	document.getElementById("total_users").value = total_users;
});

This tutorial is created in core PHP and vanilla Javascript, but may be you were working in Laravel or in any other framework, so you might face minor problems to integrate this in your scenario. If you face any issue, you can always contact us and we will help you out.

That’s how you can show realtime website users counter in your website using PHP and Node JS.

[wpdm_package id=’233′]