Creating user online program with php
This tutorial script will guide you to show how much user online on a specific period of time on your website, all is count to total user online since specific time. The idea is recording every request based on session id in php. Different session means different browser (visitor). Each different session count into total as total visitor. You can place this script at the first of your php script AFTER session_start() and connected to mysql database.
Table to store visitor request data
We need two mysql table to store visitor data from every request that visitor made such as, request page, IP, Proxy, and the request time.
Creating mysql table to store visitor data :
Table structure to store visitor data.
CREATE TABLE `member_online` ( `SID` varchar(50) NOT NULL default '', `reqTime` int(50) default NULL, `visitorType` varchar(200) default NULL, `proxy` varchar(200) default NULL, `ip` varchar(200) default NULL, `reqURI` varchar(255) default NULL, PRIMARY KEY (`SID`) );
We also need another table to store total visitor data.
CREATE TABLE `visitor_count` ( `id` int(10) NOT NULL auto_increment, `start_date` int(20) default '0', `counter` bigint(25) default '0', `countmax` bigint(25) default NULL, `countmin` int(5) default NULL, `maxdate` datetime default NULL, `mindate` datetime default NULL, `aktif` varchar(20) default 'Active', PRIMARY KEY (`id`) );
Insert one record in visitor_count for initial data :
INSERT visitor_count VALUES ('',UNIX_TIMESTAMP(now()),0,0,0,now(),now(),'Active');
You can download all tutorial files
PHP Script to store visitor data
This script must be include on every php file on your web you wish to track.
Talking about visitors, there are human and robots. The robots or bot or crawler generally came from search engine browser such as Yahoo, Google, MSN, etc, but some also came from cracker to collecting specific information such as email, they use this to deliver spam content. As this case, we need to detect if the visitor is a bot or a human based on $_SERVER['HTTP_USER_AGENT'], if you like, you can read more on detecting search engine bot name .
Detecting browser user agent, this function will detect agent type, returning user agent type, or false if not included as bot.
/** spider robot detector return spider name, or else return false **/
function crawlerDetect($USER_AGENT) {
$crawlers = array(
array('Google', 'Google'),
array('msnbot', 'MSN'),
array('Rambler', 'Rambler'),
array('Yahoo', 'Yahoo'),
array('AbachoBOT', 'AbachoBOT'),
array('accoona', 'Accoona'),
array('AcoiRobot', 'AcoiRobot'),
array('ASPSeek', 'ASPSeek'),
array('CrocCrawler', 'CrocCrawler'),
array('Dumbot', 'Dumbot'),
array('FAST-WebCrawler', 'FAST-WebCrawler'),
array('GeonaBot', 'GeonaBot'),
array('Gigabot', 'Gigabot'),
array('Lycos', 'Lycos spider'),
array('MSRBOT', 'MSRBOT'),
array('Scooter', 'Altavista robot'),
array('AltaVista', 'Altavista robot'),
array('IDBot', 'ID-Search Bot'),
array('eStyle', 'eStyle Bot'),
array('Scrubby', 'Scrubby robot')
);
foreach ($crawlers as $c) {
if (stristr($USER_AGENT, $c[0])) {
return($c[1]);
}
}
return false;
}
Record what visitor was request based on $_SERVER variable IP, request URL, request time, etc. This init function checks if current session name is on the table, if not yet, all of this data will stored in a member_online table. If current session name was in the table, they will be updated with new time and new request URL. And last, will update (increase by one) of the total visitor at table visitor_count.
/** count number of online visitor based on session time **/
function init_visitor_count () {
# collecting necessary information such IP, proxy, useragent, etc
$reqURI = strip_tags( htmlentities( $_SERVER['REQUEST_URI']));
$proxy = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = $_SERVER['REMOTE_ADDR'];
$crawler = crawlerDetect($_SERVER['HTTP_USER_AGENT']);
$visitorType = '';
if ($crawler){
$visitorType = 'bot';
}
# check if current session already on table
$query = mysql_query ("SELECT SID FROM member_online WHERE SID = '". session_id() ."'");
if (mysql_num_rows($query) != 0) {
#update / renew session timestamp on current session
$query = mysql_query("UPDATE member_online SET reqTime = UNIX_TIMESTAMP(), reqURI='$reqURI' WHERE SID = '". session_id() ."'");
}else {
# record Session ID on each request
$query = mysql_query("INSERT member_online VALUES ('".session_id()."', UNIX_TIMESTAMP(), '$visitorType', '$proxy', '$ip', '$reqURI' )");
# update total visitor count
$queryUp = mysql_query("UPDATE visitor_count SET counter=counter+1 WHERE aktif='Active'");
}
}
After all visitor data stored on a table, now we create the function to get the statistic how much user online in a specific period of time, in this case we use 900 seconds (15 minutes), and how much total user online since period of time from table visitor_count.
This function will query the count the number of human and bot request in table user_online, this is the visitor and bot online data. Next step is to select data from table visitor_count to get total visitor from a period of time. Returned value is array of current visitor human online; robot online; total visitor; date where statistic start.
/** get user online, return array of useronline, total, date count start **/
function get_user_online () {
$lastTime = mktime() - 900; // last 15 minutes
$num_bot = 0;
$num_no_bot = 0;
$visitor = 0;
# count visitor
# bot
$queryA = mysql_query("SELECT COUNT(SID) FROM member_online WHERE visitorType = 'bot' AND reqTime > $lastTime ");
if (@mysql_num_rows($queryA) != 0) {
$row = mysql_fetch_array($queryA);
$num_bot = $row[0];
}
# not bot
$queryB = mysql_query("SELECT COUNT(SID) FROM member_online WHERE (visitorType = '' OR visitorType IS NULL) AND reqTime > $lastTime ");
if (@mysql_num_rows($queryB) != 0) {
$row = mysql_fetch_array($queryB);
$num_no_bot = $row[0];
}
# total visitor
$visitor = 0;
$query2 = mysql_query("SELECT * FROM visitor_count WHERE aktif='Active' LIMIT 1");
if (mysql_num_rows($query2) != 0) {
$row = mysql_fetch_assoc($query2);
$dateStart = date('d F Y',$row['start_date']);
$visitor = number_format( $row['counter'],'','','.');
}
#delete last 1 hour session (3600 sec);
$pastTime = mktime() - 3600;
$query = mysql_query("DELETE FROM member_online WHERE waktu <= $pastTime");
return array($num_no_bot,$num_bot,$visitor,$dateStart);
}
Example call function to get a current visitor online.
list($visitor_online, $bot_online, $total_visitor, $date_statistic) = get_user_online(); $total_online = $visitor_online + $bot_online; echo ' Visitor online : '. $total_online. '. Human : ' .$visitor_online.'. Robot : '.$bot_online .'. Total visitor : '.$total_visitor.' since : '.$date_statistic.' ';
OK, that’s all, now you can try out your self.
Download example
Download PHP Script and SQL dump visitor online count example.
Related posts:
- Export MySQL table to Excel file using php script
- PHP Array to breadcrumb UL list
- Detect search engine robot on your website
- Handling file upload using PHP Script
- PHP script for reading RSS