A Persistent Hit Counter for your Web Site in ASP


The global.asa File

<SCRIPT LANGUAGE=VBScript RUNAT=Server>

Sub Session_OnStart

	Dim fo, fh, hits

	Const filename = "pageHits.txt"
	hits = 0

	Set fo = CreateObject("Scripting.FileSystemObject")

	If fo.FileExists (filename) = True Then
		Set fh = fo.OpenTextFile (filename, ForReading, False, TriStateFalse)
		hits = CInt(fh.ReadAll)
		fh.Close
		Set fh = Nothing
	End If
		
	hits =  hits + 1

	Set fh = fo.OpenTextFile (filename, ForWriting, True, TriStateFalse)
	fh.Write CStr(hits)
	fh.Close
	Set fh = Nothing

	Application("PageHits") = hits

	Set fo = Nothing

End Sub

</SCRIPT>

The hitcount.asp Page

Note that the images are named from 0, 1, ... , 9.gif.

<% @ LANGUAGE = VBScript %>
<% Option Explicit %>

<% Response.ContentType = "text/html" %>

<HTML>

<HEAD>

<TITLE>A Persistent Hit Counter for your Web Site in AS</TITLE>

</HEAD>

<BODY>

<%

Const numerals = 7
Dim i, j, k, strNumerals
	
i = Len(Application("PageHits"))
j = numerals - i
	
For k = 1 To j
	Response.Write "<img SRC=""images/counter/B.gif"" WIDTH=""15"" HEIGHT=""20"" BORDER=""0"">" & vbCrLf
Next
	
strNumerals = CStr(Application("PageHits"))
For k = j + 1 To numerals
	Response.Write "<img SRC=""images/counter/" & substr(strNumerals, (k - j), 1) & ".gif"" WIDTH=""15"" HEIGHT=""20"" BORDER=""0"">" & vbCrLf
Next

Function substr (str, start, length)
	
	Dim lstr

	If start > Len(str) OR length < 1 Then
		substr = ""
		Exit Function
	End If

	lstr = Right (str, Len(str) - (start - 1))
	lstr = Left (lstr, length)

	substr = lstr

End Function

%>

</BODY>
</HTML>