Track visitors with PHP
Tracking our website’s visitors is a very important step if you’re serious enough about analyzing your traffic and optimizing your pages to get the most of your visitors.
Create a MySql based tracking script written in PHP which will do a simple task - store each visitor that browsed our page with IP, hours, dates, browser types, reffering url and visited page. Now that our database is created all we need at this moment is a table that will store our data. We will call it “visitors_table”. The table will have 9 rows as following:
CREATE TABLE `visitors_table` (
`ID` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`visitor_ip` VARCHAR( 32 ) NULL ,
`visitor_browser` VARCHAR( 255 ) NULL ,
`visitor_hour` SMALLINT( 2 ) NOT NULL DEFAULT ‘00′,
`visitor_minute` SMALLINT( 2 ) NOT NULL DEFAULT ‘00′,
`visitor_date` TIMESTAMP( 32 ) NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`visitor_day` SMALLINT( 2 ) NOT NULL ,
`visitor_month` SMALLINT( 2 ) NOT NULL ,
`visitor_year` SMALLINT( 4 ) NOT NULL ,
`visitor_refferer` VARCHAR( 255 ) NULL ,
`visitor_page` VARCHAR( 255 ) NULL
) TYPE = MYISAM ;
We will need to setup a script which will store the visitor’s info in our database so let’s start writing it. We need the ip address of our visitor so we will get it using the following method.
$visitor_ip = GetHostByName($REMOTE_ADDR);
next we need the browser type of our visitor and we will use this function to get it:
function getBrowserType () {
if (!empty($_SERVER[’HTTP_USER_AGENT’]))
{
$HTTP_USER_AGENT = $_SERVER[’HTTP_USER_AGENT’];
}
else if (!empty($HTTP_SERVER_VARS[’HTTP_USER_AGENT’]))
{
$HTTP_USER_AGENT = $HTTP_SERVER_VARS[’HTTP_USER_AGENT’];
}
else if (!isset($HTTP_USER_AGENT))
{
$HTTP_USER_AGENT = ‘’;
}
if (ereg(’Opera(/| )([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[2];
$browser_agent = ‘opera’;
}
else if (ereg(’MSIE ([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘ie’;
}
else if (ereg(’OmniWeb/([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘omniweb’;
}
else if (ereg(’Netscape([0-9]{1})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘netscape’;
}
else if (ereg(’Mozilla/([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘mozilla’;
}
else if (ereg(’Konqueror/([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘konqueror’;
}
else
{
$browser_version = 0;
$browser_agent = ‘other’;
}
return $browser_agent;
}
so there it is:
$visitor_browser = getBrowserType();
Now lets get the hour, minute, day, month and year of this visit:
$visitor_hour = date(”h”);
$visitor_minute = date(”i”);
$visitor_day = date(”d”);
$visitor_month = date(”m”);
$visitor_year = date(”y”);
next we need to find out who is sending us visitors so we can thank them.
$visitor_refferer = gethostbyname($HTTP_REFERER);
to get the full url of our page we will use this function:
function selfURL() {
$s = empty($_SERVER[”HTTPS”]) ? ‘’ : ($_SERVER[”HTTPS”] == “on”) ? “s” : “”;
$protocol = strleft(strtolower($_SERVER[”SERVER_PROTOCOL”]), “/”).$s;
$port = ($_SERVER[”SERVER_PORT”] == “80″) ? “” : (”:”.$_SERVER[”SERVER_PORT”]);
return $protocol.”://”.$_SERVER[’SERVER_NAME’].$port.$_SERVER[’REQUEST_URI’];
}
function strleft($s1, $s2) { return substr($s1, 0, strpos($s1, $s2));
}
ok so we have our page, we will store it on a variable:
$visited_page = selfURL();
We will create a new page which will be used to connect to the database and to store our functions. Let’s name it visitors_connections.php. we will paste this code and save it:
$hostname_visitors = “host”;
$database_visitors = “database”;
$username_visitors = “username”;
$password_visitors = “password”;
$visitors = mysql_connect($hostname_visitors, $username_visitors,
$password_visitors) or rigger_error(mysql_error(),E_USER_ERROR);
function getBrowserType () {
if (!empty($_SERVER[’HTTP_USER_AGENT’]))
{
$HTTP_USER_AGENT = $_SERVER[’HTTP_USER_AGENT’];
}
else if (!empty($HTTP_SERVER_VARS[’HTTP_USER_AGENT’]))
{
$HTTP_USER_AGENT = $HTTP_SERVER_VARS[’HTTP_USER_AGENT’];
}
else if (!isset($HTTP_USER_AGENT))
{
$HTTP_USER_AGENT = ‘’;
}
if (ereg(’Opera(/| )([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[2];
$browser_agent = ‘opera’;
}
else if (ereg(’MSIE ([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘ie’;
}
else if (ereg(’OmniWeb/([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘omniweb’;
}
else if (ereg(’Netscape([0-9]{1})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘netscape’;
}
else if (ereg(’Mozilla/([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘mozilla’;
}
else if (ereg(’Konqueror/([0-9].[0-9]{1,2})’, $HTTP_USER_AGENT, $log_version))
{
$browser_version = $log_version[1];
$browser_agent = ‘konqueror’;
}
else
{
$browser_version = 0;
$browser_agent = ‘other’;
}
return $browser_agent;
}
function selfURL() {
$s = empty($_SERVER[”HTTPS”]) ? ‘’ : ($_SERVER[”HTTPS”] == “on”) ? “s” : “”;
$protocol = strleft(strtolower($_SERVER[”SERVER_PROTOCOL”]), “/”).$s;
$port = ($_SERVER[”SERVER_PORT”] == “80″) ? “” : (”:”.$_SERVER[”SERVER_PORT”]);
return $protocol.”://”.$_SERVER[’SERVER_NAME’].$port.$_SERVER[’REQUEST_URI’];
}
function strleft($s1, $s2) { return substr($s1, 0, strpos($s1, $s2)); }
function paginate($start,$limit,$total,$filePath,$otherParams) {
global $lang;
$allPages = ceil($total/$limit);
$currentPage = floor($start/$limit) + 1;
$pagination = “”;
if ($allPages>10) {
$maxPages = ($allPages>9) ? 9 : $allPages;
if ($allPages>9) {
if ($currentPage>=1&&$currentPage4) ? ” … ” : ” “;
$minPages = ($currentPage>4) ? $currentPage : 5;
$maxPages = ($currentPage”.$i.” ” : ““.$i.” “;
}
$pagination .= ($currentPage”.$i.” ”
: ““.$i.” “;
}
}
if ($currentPage>1) $pagination = “FIRST “.$pagination;
if ($currentPage> LAST“;
echo ‘
‘;
}
Ok…we have all the details stored in variables so we need to write them into our database. We will create a new file called “visitor_tracking.php” and include it in every page that we want to track:
require_once(’visitors_connections.php’);//the file with connection code and functions
//get the required data
$visitor_ip = GetHostByName($REMOTE_ADDR);
$visitor_browser = getBrowserType();
$visitor_hour = date(”h”);
$visitor_minute = date(”i”);
$visitor_day = date(”d”);
$visitor_month = date(”m”);
$visitor_year = date(”Y”);
$visitor_refferer = GetHostByName($HTTP_REFERER);
$visited_page = selfURL();
//write the required data to database
mysql_select_db($database_visitors, $visitors);
$sql = “INSERT INTO visitors_table (visitor_ip, visitor_browser, visitor_hour,
visitor_minute, visitor_date, visitor_day, visitor_month, visitor_year,
visitor_refferer, visitor_page) VALUES (’$visitor_ip’, ‘$visitor_browser’,
‘$visitor_hour’, ‘$visitor_minute’, ‘$visitor_date’, ‘$visitor_day’, ‘$visitor_month’,
‘$visitor_year’, ‘$visitor_refferer’, ‘$visitor_page’)”;
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
We have everything we need except for a page to display our data. We will start by creating a new page called display_visits.php where we paste the following code:
require_once(’visitors_connections.php’);//the file with connection code and functions
if ($_GET[’start’] == “”) $start = 0;
else $start = $_GET[’start’];
$limit = 15;
$additionalQuery = “SQL_CALC_FOUND_ROWS “;
mysql_select_db($database_visitors, $visitors);
$query_visitors = “(SELECT “.$additionalQuery.” * FROM visitors_table WHERE”;
if ($_POST[’day’]!=”") {
$query_visitors .= ” visitor_day = ‘”.$_POST[’day’].”‘”;
} else {
$query_visitors .= ” visitor_day = “.date(”d”).”";
if ($_POST[’month’]!=”") {
$query_visitors .= ” AND visitor_month = ‘”.$_POST[’month’].”‘”;
} else {
$query_visitors .= ” AND visitor_month = “.date(”m”).”";
}
if ($_POST[’year’]!=”") {
$query_visitors .= ” AND visitor_year = ‘”.$_POST[’year’].”‘”;
} else {
$query_visitors .= ” AND visitor_year = “.date(”Y”).”";
}}
$query_visitors .= ” LIMIT $start,$limit)”;
$insert_visitors = mysql_query($query_visitors, $visitors) or die(mysql_error());
$row_visitors = mysql_fetch_assoc($insert_visitors);
$totalRows_visitors = mysql_num_rows($insert_visitors);
$nbItems = mysql_result(mysql_query(”Select FOUND_ROWS() AS nbr”),0,”nbr”);
if ($nbItems>($start+$limit)) $final = $start+$limit;
else $final = $nbItems;
echo ‘
