PHP: Simple Online Users counter
Today I am going to show you how you can create a simple online users counter through php and mysql. For this tutorial you should have some basic knowledge about php and mysql queries.
First of all, you will need a database and a table where we will store information about the online visitors. The table that we will use should have the following 3 fields:
- id as autonumbe, primary field
- ip - varchar(25) to hold the ip address of the online visitors, and
- timeout - datetime where we will store the stay time of visitors
Name the table as "tblonlineusers", or if you find it difficult to create table, I've included the sql to create the required table making the task easier for you.
Now, you just need to use the following code, which has instructions in every line:
//Change the below parameters according to your server's config
$host = "localhost";
$username = "root";
$password = "password";
$con = mysql_connect($host, $username, $password); //Connect to MySql server
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = "onlineuserdb"; //Database Name
mysql_select_db($db, $con) or die(mysql_error()); //Select the provided db
//Procedures to add/update online visitors:
$timeout = date("Y-m-d H:i:s" ,time() + (5 * 60)); //The amount of time to keep the visitor online (5 represents 5 minutes, you can change it)
$ip = $_SERVER['REMOTE_ADDR']; //Retrieving ip of the current visitor
$query = "select * from tblonlineusers where ip='$ip'"; //This query will check if this visitor is already in db or not
$result = mysql_query($query) or die("Error 1: " . mysql_error());
if(mysql_num_rows($result) > 0 ) //If yes, then visitor is has opened another page
{
$query = "update tblonlineusers set timeout='$timeout' where ip='$ip'"; //Now just update visitor's record by updating his timeout
}
else
{
$query = "insert into tblonlineusers(ip,timeout) values('$ip', '$timeout')"; //If no record present then insert it into db
}
mysql_query($query) or die("Error 2: " . mysql_error()); //Execute the query
mysql_query("delete from tblonlineusers where timeout < '" . date("Y-m-d H:i:s" ,time()) . "'" ) or die("Error 3: " . mysql_error()) ; //Now delete those visitors whos timeout has elapsed
//Displaying online users:
$result = mysql_query("select count(id) from tblonlineusers");
$row = mysql_fetch_row($result);
$onlineUsers = $row[0];
echo($onlineUsers . " Users Online!"); //You can customize it according to your requirement
?>
Tags: php, stats














