Tracking Website Statistics with PHP

If you have a website, especially one that sells products or services, it can be useful to track the visitors to your site. This article explains how to write a program that will do just that.

Introduction

In this article we are going to discuss how to create a program that will track the visitors to your site. We are going to do this by:

  • Recording the visitors’ IP address.
  • Recording the time and date of the visit.
  • Recording the pages the visitor viewed.
  • Recording the name of the browser the visitor is using.
  • Recording the page the person came from.

All this will be recorded for every page on a website, simply by including the code that we are going to create in a moment.

All this information is going to give us the ability to know which pages are viewed the most and which ones the least. It will also let us know what pages a particular visitor views the most, by means of the visitor’s IP address.

The Database Table

Create a database and give it whatever name you like. We now need to create a table. We need the following data:

IP address -Visitor’s IP address

Date_visited

Page- Page visited

Browser-Name of the browser

frompage- Page from which the person came

With the above in mind, let’s create the table:

CREATE TABLE `statTracker` (
  `id` int(11) NOT NULL auto_increment,
  `browser` varchar(255) NOT NULL default ”,
  `ip` varchar(15) NOT NULL default ”,
  `thedate_visited` date NOT NULL default ‘0000-00-00′,
  `page` varchar(70) NOT NULL default ”,
  `from_page` varchar(200) NOT NULL default ”,
  PRIMARY KEY  (`id`)
) TYPE=MyISAM AUTO_INCREMENT=8 ;

The table should be very easy for you to understand. Now, without further ado, let’s create the core tracking script. This is the script that you should attach to every page on your site:

Script: theCollector.php

<?
//collect information…
$browser  =$_SERVER['HTTP_USER_AGENT']; // get the browser name
$curr_page=$_SERVER['PHP_SELF'];// get page name
$ip  =  $_SERVER['REMOTE_ADDR'];   // get the IP address
$from_page = $_SERVER['HTTP_REFERER'];//  page from which visitor
came
$page=$_SERVER['PHP_SELF'];//get current page
//Insert the data in the table…
$query_insert  =”INSERT INTO stattracker
(browser,ip,date_visited,page,from_page) VALUES
(‘$browser’,’$ip’,now(),’$page’,’$from_page’)” ;
$result=mysql_query ( $query_insert);
if(!$result){
die(mysql_error());
}

//remove this section when attaching the script to a webpage
//I include it only because of it’s debug value.
$query=”Select Count(*) from stattracker WHERE page = ‘$curr_page'”;
$result=mysql_query($query);
$viewed = mysql_result($result,0,’count(*)’);
echo “This page was viewed $viewed times”;
?>

This script includes two sections, one to collect the data we require, and one to insert the collected data into the database.

There are only a few points about the code worth explaining. The “$_SERVER[]” is a server array that contains a lot of useful variables. You can determine the host name, remote port or even the scriptname.

The Count(*) retrieves all the rows in the table that meets the condition. In the  “$viewed = mysql_result($result,0,’count(*)’)” line the “0” refers to the row; at this point there is no row in the table since we have not run the script yet.

{mospagebreak title=Analyzing the Recorded Data}

From the information collected above, we can divide the data into three main specific information areas:

Website Info:  How many visitors, browsers used, and pages visited.

Visitor Info: Pages visited, browsers used, and date of visit.

Page Info : Who visited a particular page, how many times, when and browser used.

To get this information all we have to do is run some very specific SQL queries:

Website Specific Analysis

To count how many people visited the site, run the following code:

$query = “SELECT COUNT(*) FROM stattracker GROUP by ip”;
$result=mysql_query($query);
$number_of_views = mysql_num_rows($result);

This will count all the different IP addresses in the table. If one person with the same IP address views this site a hundred times, the result of this query will be one; the same thing happens if the person views this site two hundred times.

Number of times a particular browser has been used to visit the site:

$query = “SELECT *,count(*) FROM stattracker GROUP by browser”;
$result=mysql_query($query);
while ($row =mysql_fetch_array($result)) {
echo “browser  name = ” .$row['browser']. ” Used: ” .$row ['count
(*)'];
}

The above query checks how many time a particular browser has been used to visit the site.

{mospagebreak title=Visitor Specific Analysis}

Number of times user visited:

$query = “SELECT count(*) FROM stattracker WHERE ip =
‘127.0.0.1’”;
$result=mysql_query($query);
while ($row =mysql_fetch_array($result)) {
echo “Visited ” .$row['count(*)']. ” times”;
}

Here I’m checking how many times a particular user visited the site. In this case the visitor is identified by their IP address.

Pages user visited

$query = “SELECT *,count(*) FROM stattracker WHERE ip =
‘127.0.0.1’ GROUP BY page”;
$result=mysql_query($query);
while ($row =mysql_fetch_array($result)) {
echo “Page: ” .$row['page']. “Viewed: “.$row['count(*)']. “<br>”;
}

Browser used when visiting

$query = “SELECT *,count(*) FROM stattracker WHERE ip =
‘127.0.0.1’ GROUP BY browser”;
$result=mysql_query($query);
while ($row =mysql_fetch_array($result)) {
echo “Browser used: ” .$row['browser']. “Used: “.$row['count
(*)']. “times<br>”;
}

Number of visits by this user in last 30 days:

$query = “SELECT *,COUNT(*) FROM stattracker WHERE ip =
‘127.0.0.1’ AND DATE_SUB(CURDATE(),INTERVAL 30 DAY) GROUP BY
page”;
$result=mysql_query($query);
while ($row =mysql_fetch_array($result)) {
echo “Page: ” .$row['page']. “Viewd: “.$row['COUNT(*)']. “times<br>”;
}

Page Specific Analysis

How many times a particular page has been visited:

$query = “SELECT count(*) FROM stattracker WHERE page =
‘/pagename.php'”;
$result=mysql_query($query);
while ($row =mysql_fetch_array($result)) {
echo “Visited ” .$row['count(*)']. ” times”;
}

Who visits this page?

$query = “SELECT *,count(*) FROM stattracker WHERE page =
‘/pagename.php’ GROUP BY ip”;
$result=mysql_query($query);
while ($row =mysql_fetch_array($result)) {
echo “Visited ” .$row['count(*)']. ” times. By: “.$row['ip'];
}

{mospagebreak title=Building a Page}

So, let’s build a PHP page to display this information. Create a new PHP document, call it index.php and add the following code:

Script: index.php

<?
include “trdbcon.php”;
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-
8859-1″ />
<title>Untitled Document</title>
<style>
.{
font-size:12px;}
</style>
</head>
<body>
<strong>WebSite Statistics</strong>
<br />
<table width=”100%” border=”1″ cellspacing=”1″ bordercolor=”#FF0000″>
  <tr>
    <td width=”16%”><strong>No. Visitors </strong></td>
    <td width=”24%”><strong>Date Visited </strong></td>
    <td width=”25%”><strong>Browsers Used </strong></td>
    <td width=”35%”><strong>Pages Visited </strong></td>
  </tr>
  <?
  $query = “SELECT *,COUNT(*) FROM stattracker GROUP by ip”;
$result=mysql_query($query);
$number_of_views = mysql_num_rows($result);
if($number_of_views>0){
while($row=mysql_fetch_assoc($result)){ 

  ?>
  <tr valign=”top”>
    <td><?=$number_of_views;?></td>
    <td><?=$row['date_visited'];?></td>
    <td><?=$row['browser'];?></td>
    <td><?=$row['page'];?></td>
  </tr>
  <? }
  }else{
   ?>
  <tr><td><p>No Results</p></td></tr>
  <? }?>
</table>
<br />
<strong>Visitor Statistics</strong>
<br />
<table width=”100%” border=”1″ cellspacing=”1″ bordercolor=”#FF0000″>
  <tr>
    <td width=”16%”><strong>Visitors ID </strong></td>
    <td width=”24%”><strong>Date Visited </strong></td>
    <td width=”25%”><strong>Browser Used </strong></td>
    <td width=”35%”><strong>Pages Visited </strong></td>
  </tr>
   <?
 $queryV = “SELECT *,COUNT(*) FROM stattracker WHERE ip =
‘127.0.0.1’ GROUP by page”;
$resultV=mysql_query($queryV);
$visitors = mysql_num_rows($resultV);
if($visitors>0){
while ($rowV =mysql_fetch_assoc($resultV)) {
//echo “Visited ” .$row['count(*)']. ” times”;

  ?> 

  <tr valign=”top”>
    <td><?=$rowV['ip'];?></td>
    <td><?=$rowV['date_visited'];?></td>
    <td><?=$rowV['browser'];?></td>
    <td><?=$rowV['page'];?></td>
  </tr>
  <? }
  }else{
   ?>
  <tr><td><p>No Results</p></td></tr>
  <? }?>
</table>
<br />
<strong>Page Statistics</strong>
<br />
<table width=”100%” border=”1″ cellspacing=”1″
bordercolor=”#FF0000″ >
  <tr>
    <td width=”16%”><strong>Page Name </strong></td>
    <td width=”24%”><strong>No. Visits </strong></td>
    <td width=”25%”><strong>Visited By </strong></td>
    <td width=”35%”><strong>Referred from Page </strong></td>
  </tr>
  <?
  $queryP = “SELECT *,count(*) FROM stattracker WHERE ip =
‘127.0.0.1’ GROUP BY page”;
$resultP=mysql_query($queryP);
if($visitors>0){
while ($rowP =mysql_fetch_assoc($resultP)) {
//echo “Page: ” .$row['page']. “Viewed: “.$row['count(*)']. “<br>”;
?>
   <tr valign=”top”>
    <td><?=$rowP['page'];?></td>
    <td><?=$rowP['count(*)'];?></td>
    <td><?=$rowP['ip'];?></td>
    <td><?=$rowP['from_page'];?></td>
  </tr>
  <? }
  }else{
   ?>
  <tr><td><p>No Results</p></td></tr>
  <? }?>
</table>
</body>
</html>

What this entire code does is display the three main sets of information as we’ve discussed previously. It is only a very general snapshot of who visited what page when and what browser they used. You even get the total number of times a particular page was visited.

Another area of analysis that I haven’t discussed here is breaking the information down by the date of visit. You can for example run a query to find out the number of times a particular person visited in a month or year. There is just so much that you can do with the information that is collected by the script. There is no single best way of getting this information out, because it depends entirely on individual needs.

Create two more PHP pages and call them p1.php and p2.php.  Include the ‘theCollector.php’ page in both of them. In the p1 one, add a link to p2 and in p2 add a link to p1. These two pages are going to be our test pages.

Here’s the code for p1.php. Use the exact same code when you create p2.php:

Script: p1.php

<?
include “theCollector.php”;
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-
8859-1″ />
<title>Untitled Document</title>
</head>
<body>
<p><a href=”p1.php”>page1</a></p>
<p><a href=”p2.php”>page2</a></p>
</body>
</html>  

Run p1.php, click on the link to p2.php and then click on the link to p1.php. Repeat this process a couple of times. This will populate the table with some data for us to use later on.

Conclusion

With the information that you get from the collector script, you can extract a lot more information than I did in this article. You can even use PHP’s gd to give a graphical view of your web stats. But for most web masters, this should be adequate or act as a base to write more advanced web statistics scripts.

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye