How to Create a "Down and Dirty" Filesystem Object Page Counter.

By Peter A. Bromberg, Ph.D.

Peter Bromberg  

Sometimes the simplest solutions are the most elegant when you have a need. Sure, your site might be running Webtrends or have a sophisticated user tracking system. But a lot of times I've found that I may have a single page that I've put up for some special purpose and all I really need to know is how many times it's been loaded by visitors since I put it up, and that's all I really am interested in.

This is where a trick with the IMG tag and the VBSCript / Javascript FileSystemObject interface become useful. By inserting an IMG tag into your .HTM or .ASP page whose source is not an image, but an ASP page, you have the flexibility to increment a counter in a text file, and then serve up an actual image to the IMG tag (if that's what you want; you don't have to at all) and the IMG tag will be none the wiser.



To do this, you create an image tag, usually at the very bottom of your page, that looks like this:

<img src="counter.asp" width=0 height=0>

In this particular case, I don't want anything visible on the page, all I want to do is run the Counter.asp page, and that's what the above tag will do.

The counter.asp page looks like so:

<%
dim fs, F,tf
on error resume next
set fs=server.createobject("scripting.filesystemobject")
Set F = fs.OpenTextFile(Server.mappath("count.txt"),1)
iCounter = F.ReadAll
F.Close
iCounter = iCounter+1
Set tf =fs.CreateTextFile(Server.mappath("count.txt"),True)
tf.WriteLine(iCounter)
tf.Close
Response.ContentType="image/gif"
Response.write "."
%>

All we're doing here is opening a text file "count.txt", reading the contents into the ICounter variable, incrementing the variable by 1, and then creating a new text file of the same name and writing the updated iCounter to it. To check our results, all we need to do is point our browser to the "count.txt" file and see the number it holds.

Of course, you'll need to have write permission enable to the folder that count.txt resides in, or at least write permission to the file itself.

Note that at the bottom I set the content type to "image/gif" but all I do here is write out a DOT ("."). You could instead use Response.Redirect "Somepic.gif" and actually return a real image to the IMG tag if that's what you want. You can get a lot more sophisticated with this technique by using the IMG tag to actually write a bunch of Javascript to the visitor's browser where it's the Javscript itself that writes out the IMG tag plus whatever other code you need, , get some metrics, and return them to the ASP page on the querystring of the image tag src reference to the ASP page for processing into your database.

Peter Bromberg is an independent consultant specializing in distributed .NET solutionsa Senior Programmer /Analyst at in Orlando and a co-developer of the NullSkull.com developer website. He can be reached at info@eggheadcafe.com