This is one common thing you will  find on lot of websites. I always think of it as encouraging people to visit the site because knowing number of people on the website might motivate visitors to often visit the site. For example, if you have a social network and you want to create that statistical information at the login page of the site, it can be cool for members of the site. So I want to go through just some simple way of getting this done using PHP and relying on  a MYSQL database.  I will add comment to the scripts to fully explain each of the steps and I will assume writing the script to display number of users online on 2smart4school.

$server = “localhost”; // Your mySQL Server, most cases “localhost”
$db_user = “2smart4school”; // Your mySQL Username
$db_pass = “2smart4school”; // Your mySQL Password
$database = “2smart4school”; // Database Name

$timeoutseconds = 300; // Timeout value in seconds

$timestamp=time();  // capturing the current time

$timeout=$timestamp-$timeoutseconds; // this is time to check if someone who was online is no more or timed out.
mysql_connect($server, $db_user, $db_pass) or die (“2smart4school Database CONNECT Error”);  //connect to the database using our info or display error
mysql_db_query($database, “INSERT INTO useronline VALUES (‘$timestamp’,’$REMOTE_ADDR’,’$PHP_SELF’)”) or die(“Useronline Database INSERT Error”);

// The table useronline keeps information on all visitors online to the site.
mysql_db_query($database, “DELETE FROM useronline WHERE timestamp<$timeout”) or die(“Useronline Database DELETE Error”);

//Delete users who have timed out
$result=mysql_db_query($database, “SELECT DISTINCT ip FROM useronline WHERE file=’$PHP_SELF'”) or die(“Useronline Database SELECT Error”);

// get resulset of all distinct ips recorded in the useronline table. Ip is just the remote addresses we inserted into the usersonline table
$user =mysql_num_rows($result);  // get the number of rows in the result set
mysql_close();  // close the connection to the database
if ($user==1) {echo”$user User online”;} else {echo”$user Users online”;}

//output the number of users online.
?>

//end of script.

 

So how can you use the script you may ask? This can be written and stored on the server and be included on any page of the website such as the footer of the home page to display the number of users online. For example, you can create a file in notepad with the script above and save it on the server as usersonline.php. After that, lets say you want to show the users on the home page, then you can create the home page like below

<html>
<body>
<h1>Welcome to 2smart4school</h1>
<p>This site is about bla bla bla bla</p>

<?php include ‘usersonline.php’; ?>
</body>
</html>

That is it and you can include that on as many pages as you want to display the number of users online at that time.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *