When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
Technology Jobs
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this page.
Published: Friday, February 16, 2001

Capturing Basic Site Statistics

By Phil Fresle


Capturing site statistics is the basis of understanding how well the marketing of your Web site is progressing. Unless we know how many visitors we have had, what pages are most popular, where our visitors came from, and what types of browsers they are using we are left in the dark as to how to improve our web site or target visitors more effectively. This article demonstrates how we can capture site statistics quite simply and record them in an Access database.

- continued -

'

This article contains a short sample of code that can be placed in a file and imported into pages that you wish to track via a server-side include. (To learn more about server-side includes be sure to read: The Low-Down on #include!) The code for this include file is shown later on in the article, but for other reasons it is important that each of your pages that you wish to implement this basic stat tracking start with the following code (again, you can put this short code snippet in an include file as well):

<% Option Explicit
Response.Buffer = True
Response.CacheControl = "Private"
Response.Expires = -100000
%>

This code does a couple of things. By setting Response.Buffer to True our HTML output is buffered in order to speed up the initial delivery of the HTML output when we Flush it later on. (To learn more about why buffering is a performance boon be sure to read: Buffer That Output!) Next, we set the CacheControl to "Private" to try to stop our page from being cached by proxy servers, and we will set a large negative Expires value to try to stop our page from being cached by the web server or browsers. We do this because if the user is seeing cached pages our site statistics will not be being updated! (To learn more about page cache control be sure to read: Cache No More!)

All of this header code can (should) be placed in a file to be included via a server-side include. For this article we'll assume that you did this and named the file /include/StatHeader.asp.

Now let's examine the code that is responsible for updating the statistics when an ASP page is updated. This code should also be placed in an include file, we'll assume this is placed in an include file named /include/StatFooter.asp. This include file will need to be included on each page that you are interested in recording each time a page is viewed. The code for recording the stat information can be seen below:

<%
Response.Flush   'Flush the HTML output

Dim sDatabase
Dim oConnection
Dim sSQL
Dim oCommand
Dim rsResults
Dim sConnection

If Not Response.IsClientConnected Then
  Response.End
Else
  On Error Resume Next

  sDatabase= "\data\sitestats.mdb"

  Set oConnection = CreateObject("ADODB.Connection")
  oConnection.Mode = 3
  sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;"
  sConnection = sConnection & "Data Source=" & sDatabase & ";"
  sConnection = sConnection & "User Id=Admin;Password=;"
  oConnection.Open sConnection

  sSQL = "SELECT * FROM tblStats WHERE StatID=0"

  Set oCommand = Server.CreateObject("ADODB.Command")
  Set oCommand.ActiveConnection = oConnection
  oCommand.CommandText = sSQL
  oCommand.CommandType = 1

  Set rsResults = Server.CreateObject("ADODB.Recordset")
  rsResults.Open oCommand,,1,3
  Set oCommand = Nothing

  With rsResults        
    .AddNew
    .Fields("Recorded").Value=Now
    .Fields("RemoteAddress").Value = _
                  Request.ServerVariables("REMOTE_ADDR")
    .Fields("RemoteHost").Value = _
                  Request.ServerVariables("REMOTE_HOST")
    .Fields("HttpReferer").Value = _
                  Request.ServerVariables("HTTP_REFERER")
    .Fields("HttpUserAgent").Value = _
                  Request.ServerVariables("HTTP_USER_AGENT")
    .Fields("WebPage").Value = _
                  Request.ServerVariables("URL")
    .Update
    .Close
  End With
  Set rsResults = Nothing
  oConnection.Close
  Set oConnection=Nothing
End If
%>

The first thing this code does is to flush the HTML code we have generated so far to the user's browser. The rest of the ASP script will be writing our stats away and we do not want to delay the user seeing the page while this activity is completed.

We then check to make sure the client is still connected (using Response.IsClientConnected) as we do not want to waste unnecessary processing on the server. (To learn more about Response.IsClientConnected be sure to check out the technical docs.)

Next we open up a connection to the database, and use a command object to build a recordset that we can update. We use the AddNew method of the recordset to add a new recordset and assign our text to the various database table fields. Note that we add six bits of information: the time the page was visited (the current time, Now); the user's IP address (Request.ServerVariables("REMOTE_ADDR")); the user's hostname (see this FAQ for more information); the referring Web page (the page that contained a link the user clicked on to get to this page); the user's browser's User Agent string; and the URL of the ASP page itself.

Finally, we tidy up by closing our database objects and setting the variables to Nothing.

Assuming that we placed the first chunk of code we looked at today in an include file named /include/StatHeader.asp and the above chunk of code in an include file named /include/StatFooter.asp, we would create ASP pages whose traffic we wished to track using the following template:

<!--#include virtual="/include/StartHeader.asp"-->
<%
  ' -- ASP page content --
%>
<!--#include virtual="/include/StartFooter.asp"-->

Finally, the Access database needs to consist of just one table (tblStats) that has the following structure:

tblStats Table
StatIDAutoNumber
RecordedDate/Time
RemoteAddressText(20)
RemoteHostText(20)
HttpRefererText(255)
HttpUserAgentText(255)
WebPageText(255)

Having recorded the information we can analyze it to see how we might improve our Web site in the future! Happy Programming!

By Phil Fresle

Software Developer / Programmer - Distributed Systems (NYC)
Next Step Systems
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume


ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article