Classic ASP to collect visitor geographical data and ip; track visitors, and count page views.


Classic ASP Active Server Pages Examples, code, tutorials, scriptsTrack Site Visitors with Classic ASP

[This is out of date, but may be useful to someone, so I am leaving it up.] Install this code then check your database to see where your visitors come from and when. See which search engines are crawling your site.

4 scripts contained in this code: views counter to count number of times a page is viewed; track visitor to get visitor ip address and to record first and most recent datetimes of their views; get ip info which fetches ip geographical data from remote xml and puts it into database if not already in it; botcheck which attempts to place bot data in one table and human data in another.

This code queries a remote XML file at http://www.ipinfodb.com for the visitor geographical data. Please give them a donation for offering that service for free and for providing free databases you can download. I did!

I once tried using code very much like this in my global ASA file and it worked but was not feasible for a high-traffic site because having this in the global ASA file seemed to slow down site response too much.

IPINFODB has updated their API. You must register for a free API key. Also, I found that my code for inserting new records into

COUNTER STATS

Page Views
http://classicaspreference.com/aspexamples/classic_asp_track_visitors.asp
1371
table ip_group_city needs to be updated, therefore the code on this page is out of date! Thank you, Dennis, for this heads-up.

YOUR GEOGRAPHICAL VISITOR INFORMATION:

Syntax error in INSERT INTO statement.

ip_group_city
Data collected might look something like this
ID IP country_code country_name region_code region_name city zipcode latitude longitude gmtOffset dstOffset
13
0.0.0.0






0
0
0
0
12
123.201.79.42
IN
India
02
Andhra Pradesh
Visakhapatnam

17.7
83.3
5.5
5.5
11
67.195.110.172
US
United States
06
California
Sunnyvale
94089
37.4249
-122.007
-8
-7
10
89.31.88.61
RU
Russian Federation
48
Moscow City
Moscow

55.7522
37.6156
3
4
9
123.203.21.103
HK
Hong Kong
00

Central District

22.2833
114.15
8
8
8
173.2.109.254
US
United States
36
New York
Tarrytown
10591
41.0837
-73.8397
-5
-4
7
62.61.164.205
OM
Oman
06
Masqat
Muscat

23.6133
58.5933
4
4
6
94.102.49.76
NL
Netherlands
07
Noord-Holland
Amsterdam

52.35
4.9167
1
2
5
94.64.34.215
GR
Greece
03
Xanthi
Xánthi

41.1414
24.8836
2
3
4
222.210.104.149
CN
China
32
Sichuan
Chengdu

30.6667
104.067
8
8

Download sample database
 

I suggest including the following code in any page you want stats for by placing this
<!--#include file="statstracker.asp"-->
at the very bottom of the page. Place it at the bottom so that if any errors are generated, your visitors may still be able to view the page.

<%
StatsConn= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\YOURPATH\SITESTATS.mdb;"
%>
<%'GET PAGE VISITOR CAME FROM. GET VISITORS LANGUAGE
RefURL = Request.ServerVariables("HTTP_REFERER")
strLang = Request.ServerVariables("HTTP_ACCEPT_LANGUAGE")
%>
<% 'GET URL OF PAGE BEING VIEWED
'page url from http://www.powerasp.com/content/new/get-current-page-url.asp
if Request.Querystring ="" then
Thispage ="http://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("URL")
else
Thispage ="http://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("URL") & "?" & Request.Querystring
end if
%>
<% 'GIVE VISITOR A COOKIE WITH THEIR SESSION ID IF THEY ACCEPT COOKIES
if request.cookies("mySession")="" then
response.cookies("mySession") = (Session.SessionID)
Response.Cookies("mySession").Expires = Now() + 365
end if

strSessionID = request.cookies("mySession")
If strSessionID = "" then
strSessionID = "000000"
end if

'GET VISITOR IP ADDRESS
'IP address from http://www.powerasp.net/content/new/using-asp-to-retrieve-users-ip-address.asp

Dim UserIPAddress
UserIPAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If UserIPAddress = "" Then
UserIPAddress = Request.ServerVariables("REMOTE_ADDR")
End If

'GET VISITORS BROWSER TYPE. SOME OF THESE STRINGS ARE LONGER THAN 255 SO WE WILL TRUNCATE IT IF NEEDED.
strUA = Trim(Request.ServerVariables("HTTP_USER_AGENT"))
'Make sure length of the string is more than the number of characters to return
If Len(strUA) > 255 Then
strUA = Left(strUA,254)
End If
%>
<%
'IS VISITOR HUMAN OR A BOT OR A SPIDER?
'CHECK YOUR STATS TO ADD ITEMS TO THIS LIST. http://www.botsvsbrowsers.com IS GOOD FOR DETERMINING IF USERAGENT IS KNOWN BOT.
botTool = strUA

robotChk = InStr(Browser, "bot") 'check for bots and crawlers
robotChk = robotChk + InStr(botTool, "Slurp")
robotChk = robotChk + InStr(botTool, "Jeeves")
robotChk = robotChk + InStr(botTool, "HTTrack")
robotChk = robotChk + InStr(botTool, "rawler")
robotChk = robotChk + InStr(botTool, "binarycanary")
robotChk = robotChk + InStr(botTool, "Yeti")
robotChk = robotChk + InStr(botTool, "Yandex")
robotChk = robotChk + InStr(botTool, "msnbot")
robotChk = robotChk + InStr(botTool, "Googlebot")
robotChk = robotChk + InStr(botTool, "bot")
robotChk = robotChk + InStr(botTool, "pider")
robotChk = robotChk + InStr(botTool, "es_com_viewer larbin")
robotChk = robotChk + InStr(botTool, "buddybuzz")
robotChk = robotChk + InStr(botTool, "Snarfgroggle")
robotChk = robotChk + InStr(botTool, "Mediapartners-Google")
robotChk = robotChk + InStr(botTool, "FunWebProducts") 'may not be a bot but makes tracking difficult
'users with this in their browsers may have trouble keeping cookie logins
robotChk = cint(robotChk)

%>
<%
'LETS GET OUR VISITORS GEOGRAPHICAL INFORMATION
'IP DATABASES AND XML LOOKUP AT http://www.ipinfodb.com ***PLEASE GIVE THEM A DONATION*** FOR OFFERING THIS FREE SERVICE!!!!!!!!!!!!!
'xml script found at http://stackoverflow.com/questions/902554/xml-and-asp-retrieve-and-parse-a-remote-file and modified

if NOT UserIPAddress = "" then

On Error Resume Next ' prevent tossing unhandled exception
Dim URL, objXML, value

Set objXML = Server.CreateObject("MSXML2.DOMDocument.6.0")
URL = "http://ipinfodb.com/ip_query.php?ip=" & UserIPAddress

if (NOT Err.Description = "") then
'You could use the following to email an alert
'Response.Write("An error occured when retrieving data from an external source.")
'Response.Write(Err.Description)
'Response.End

else


objXML.setProperty "ServerHTTPRequest", True
objXML.async = False
objXML.Load URL
'Set oRoot = objXML.selectSingleNode("//response")


strCountry=objXML.documentElement.childNodes(2).text
strIP = objXML.documentElement.childNodes(0).text
strRegion = objXML.documentElement.childNodes(5).text
strCity = objXML.documentElement.childNodes(6).text
strRcode = objXML.documentElement.childNodes(4).text
value = objXML.documentElement.Text
'Response.Write "after setting value: " & Err.Description & "<br>"

'HERE IS AN ATTEMPT TO REDUCE CHINESE TRAFFIC AND TO KEEP CHINESE TRAFFIC FROM CLOGGING UP DATABASE
'IF CHINESE TRAFFIC IS A LEGITIMATE PART OF YOUR AUDIENCE, COMMENT OUT THE NEXT FOUR LINES
'LOGS OF ONE OF MY SITES SHOWED THAT 90 PERCENT OF THE TRAFFIC WAS CHINESE BOTS SO WE BLOCKED SOME OF IT WITH THE FIREWALL BUT THIS NEXT BIT OF CODE PROVED TO BE VERY HELPFUL
if strCountry = "CN" then
response.redirect "http://en.wikipedia.org/wiki/Tiananmen_Square_protests_of_1989"
response.end
end if


'NOW WE PUT OUR VISITOR GEOGRAPHICAL INFO INTO DATABASE IF NOT ALREADY IN IT

set conn=Server.CreateObject("ADODB.Connection")
'conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open StatsConn

strSQL = "SELECT * FROM ip_group_city WHERE IP='" & strIP &"'"
'response.write strSQL
SET oRs = conn.Execute(strSQL) 'Execute the SQL statement

if oRs.EOF then

sql="INSERT INTO ip_group_city (IP, country_code, country_name, region_code, region_name, city, zipcode, latitude, longitude, timezone,gmtOffset, dstOffset)"
sql=sql & " VALUES "
sql=sql & "('" & objXML.documentElement.childNodes(0).text & "',"
'sql=sql & "'" & objXML.documentElement.childNodes(1).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(2).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(3).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(4).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(5).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(6).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(7).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(8).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(9).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(10).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(11).text & "',"
sql=sql & "'" & objXML.documentElement.childNodes(12).text & "')"
'on error resume next
conn.Execute sql
if err<>0 then
'Response.Write Err.Description & " 214 "
else
'Response.Write("new record inserted")

end if

end if
conn.close
set conn = nothing

end if
Set objXML = Nothing
end if

%>
<%
'IF OUR VISITOR IS NOT A BOT THEN WE PUT SOME INFO ABOUT PAGE VIEW INTO DATABASE
if NOT robotChk >0 then
Dim adsConn, adsRS

' Open Connection to the database
'set conn = Server.CreateObject("ADODB.Connection")

Set adsConn = Server.CreateObject("ADODB.Connection")
adsConn.Open StatsConn
set adsRS=server.createobject("adodb.recordset")
adsRS.open "SELECT * FROM [STATS] where StatsPg = '" & ThisPage &"'", adsConn, 1, 2

if NOT adsRS.eof then

adsRS("StatViews") = adsRS("StatViews") + 1


adsRS("StatLast") = now()
'strURL = adsRS("StatUrl")
adsRS.Update
'response.write adsRS("StatLast")

else
adsRS.Close

strsql = "SELECT * FROM STATS WHERE 0 = 1"
adsRS.Open strsql, adsConn, 1, 2

adsRS.AddNew
strNow = now()
adsRS("StatsPg") = ThisPage
adsRS("StatViews") = 1
adsRS("StatStart") = strNow
adsRS("StatLast") = strNow
adsRS.Update

end if
adsRS.Close
adsConn.Close

end if
%>

<%
'IF OUR VISITOR IS NOT A BOT WE PUT INFO ABOUT THEM INTO DB
if NOT robotChk >0 then
' Open Connection to the database
set conn = Server.CreateObject("ADODB.Connection")
conn.Open StatsConn
set VisRS = Server.CreateObject("ADODB.Recordset")


strsql = "SELECT * FROM [VISITORS] where VIP = '" & UserIPAddress &"' AND Vsession="&strSessionID&""
VisRS.Open strsql, conn, 1, 2
if NOT VisRS.eof then

VisRS("Vlatest")=now()
VisRS("VuserAgent")=strUA

VisRS.Update
VisRS.Close
Set VisRS = Nothing

else

strNow = now()
strsql = "SELECT * FROM [VISITORS] WHERE 0 = 1"

set VisRSnew = Server.CreateObject("ADODB.Recordset")
'VisRS.cursorlocation = 3
VisRSnew.Open strsql, conn, 1, 2

VisRSnew.AddNew


VisRSnew("VIP") = UserIPAddress
VisRSnew("Vdate") = strNow
VisRSnew("Vlatest") = strNow
VisRSnew("Vsession") = strSessionID
VisRSnew("VuserAgent") = strUA
VisRSnew("FirstPage") = Thispage
VisRSnew("Referer") = RefURL
VisRSnew("Language") = strLang
VisRSnew("Vcountry") =strCountry
VisRSnew("Vstate") = strRegion
VisRSnew("Vregion") = strRcode
VisRSnew("Vcity") = strCity

VisRSnew.Update
VisRSnew.Close
set VisRSnew = nothing
end if
conn.Close
set conn = nothing
end if
%>

<%
'IF OUR VISITOR IS A BOT OR SPIDER THEN WE PUT THAT INFO INTO THE SPIDERSANDBOTS TABLE. WE COLLECT THIS INFO TO KNOW WHICH SEARCH ENGINES INDEX THE SITE
if robotChk >0 then
' Open Connection to the database
set conn = Server.CreateObject("ADODB.Connection")
conn.Open StatsConn
set VisRS = Server.CreateObject("ADODB.Recordset")


strsql = "SELECT * FROM [SPIDERSANDBOTS] where VIP = '" & UserIPAddress &"' AND Vsession="&strSessionID&""
VisRS.Open strsql, conn, 1, 2
if NOT VisRS.eof then

VisRS("Vlatest")=now()
VisRS("VuserAgent")=strUA

VisRS.Update
VisRS.Close
Set VisRS = Nothing

else

strNow = now()
strsql = "SELECT * FROM [SPIDERSANDBOTS] WHERE 0 = 1"

set VisRSnew = Server.CreateObject("ADODB.Recordset")
'VisRS.cursorlocation = 3
VisRSnew.Open strsql, conn, 1, 2

VisRSnew.AddNew


VisRSnew("VIP") = UserIPAddress
VisRSnew("Vdate") = strNow
VisRSnew("Vlatest") = strNow
VisRSnew("Vsession") = strSessionID
VisRSnew("VuserAgent") = botTool
VisRSnew("FirstPage") = Thispage
VisRSnew("Referer") = RefURL
VisRSnew("Language") = strLang
VisRSnew("Vcountry") =strCountry
VisRSnew("Vstate") = strRegion
VisRSnew("Vregion") = strRcode
VisRSnew("Vcity") = strCity

VisRSnew.Update
VisRSnew.Close
set VisRSnew = nothing
end if
conn.Close
set conn = nothing
end if
%>

<%
'IF VISITOR IS NOT A BOT WE ADD THEIR VIEW OF THE PAGE TO THE COUNTER FOR THAT PAGE
if NOT robotChk >0 then
'track individual page views

' Open Connection to the database
set conn = Server.CreateObject("ADODB.Connection")
conn.Open StatsConn


' Open record
strsql = "SELECT * FROM [VISITEDPAGES] WHERE 0 = 1"

set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strsql, conn, 1, 2

rs.AddNew
if NOT strSessionID > 0 then
strSessionUser = "unavailable"
else
strSessionUser = Cstr(strSessionID)
end if
rs("VisitorID") =strSessionUser
rs("Date") = now()
'rs("Latest") = x_Latest
rs("Page") = Thispage
'rs("Visits") = x_Visits
rs("Referer") = RefURL

rs.Update
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing

end if
%>



 

ASP Examples Menu of Active Server Pages scripts code Classic ASP

Classic ASP Active Server Pages Examples, code, tutorials, scriptsASP Examples Menu (below*)



Active Server Pages | ASP | Scripts | Tutorials | Code | Web Programming | Examples
Active Server Pages ASP code examples, tutorials, and snippets for use in Programming interactive websites.

If you find omissions or errors let me know. I have moved these code samples to their own domain; if you find pieces missing, please let me know.
My favorite scripts site is CODANGO.

*

If any the information I've posted here has been useful to you, please donate.

Quick 'n  easy  dirty PHP script code wizard-generator

Zenphoto RSS XML feed used as data source for javascript slide show with PHP

Classic ASP to archive emails into database and save attached files to folder

PHP Image GD for thumbnails and image resizing with pathing for Windows servers

ODBC database connections for Microsoft Access MDB files with Windows 7: solution posted on this forum.

HTML5 embedded video player "Projekktor" completely skinnable with hyperlinked watermark

Edit web.config to allow Windows iis7 server to handle mp4 files or other mime types as needed

URL rewrite or make friendly URLs for iis7 Windows Server 2008 by editing your web.config file

FACEBOOK API GEEWHIZ - INTEGRATE FACEBOOK WITH YOUR WEBSITE

Use PHP to zip folders for backing up a website

Use PHP to archive emails in database and save attached files to folder

Use PHP with json to check how many hits left on Twitter API

PHP get single record from Access database without catchable fatal error message

PHP to make a bot to send automatic Twitter status updates with Abraham Williams' PHP Oauth Twitter Library

A way to use the PHP Oauth Twitter Library with your Classic ASP scripts for sending status updates

Get user's IP address location for your form results

Tutorial for registering an application with Twitter

Update your Twitter status with Classic ASP and Oauth seamlessly and invisibly without having to login to Twitter. Send status updates programmatically from a web page. PHP example too.

CLASSIC ASP: Cache your Twitter tweets in a database to keep your Twitter xml requests within the rate limit of 350 per hour / PHP VERSION

PHP: Use json to fetch Twitter followers' profiles

Index files content and insert into database for faster searches

Classic ASP with Ajax: secure URL check

Classic ASP with Ajax: referer check

Classic ASP with Ajax: a solution to the ampersand problem in querystrings

Very Simple Star Rating System for Classic ASP

Star Rating System uses CSS and JS adapated for Classic ASP from Yvo Schaap PHP script

XMLhttp with ASP to fetch and save photos from Photobucket account through RSS XML. Can be adapted for Youtube videos to import data to database.

NET image resize can be used to make thumbnails for Classic ASP

Track site visitors, get their ip address geographical data, count page views with Classic ASP

Javascript slideshow with Classic ASP to load image details dynamically from database photos table

Classic ASP with Ajax for rotating banners without page refresh and XML file converted to recordset as banner database
--Variation of the above but fetching a REMOTE XML file as the database
--Variation checks for secure URL and builds absolute URL and makes offsite banner links open in new window

True inline edit Classic ASP datagrid table database edit updating with Ajax SIMPLE EASY without page refresh!

Use Ajax with Classic ASP to preview data then update form with javascript url write

Yvo Schaap's easy inline edit Ajax: an example of using it to inline edit multiple rows of records in Classic ASP

Use Classic ASP to send text messages SMS from your website (Also shows how to use xmlhttp to post form data)

Ajax with Classic ASP for seamless, no page reload database record insertion

Nested SQL Statements to make temporary column names

Multiple records per row with paging

Display multiple records per row

Get ID of newly inserted record, Classic ASP, Access Database

Javascript timer with ASP to keep track of time expired until login expires / timeout session is up

Multiple Javascript event functions triggered from single form onsubmit

Get Querystring key names along with querystring variables

These are out of date but may still be of interest:

ASP Youtube Downloader  Version FOUR
All ASP code. Allows user client side downloads of Youtube videos. You have the option to allow files to be saved directly to your site also.
ASP/PHP video downloader (Works better than ASP for large files)

Use ASP to dynamically parse a Youtube XML playlist to render to html.

Zip up an archive file of your site for backup if you need to restore website with ASP and free Zip Component.

Zip all files in a folder into an archive or backup file dynamically by specific file extension.

Sanitize or clean price cost field for database insertion or display.

Javascript image dimensions and image file size preview.

Put recordset into array, assign keys to the records then use record associated with specific array key as a variable elsewhere.

Access Database Interface Generator Wizard to read your table and field names and to create a table display.

Combining dropdown selection box menu with dynamic ASP database page.

How to redirect user to original page they tried to view before logging, after they are logged in.

Previous/Current/Next Records, or Buddy Ring Script

Custom ASP 404 page not found error script: can also be used for URL rewriting

ASP Example: Combine ASP with Javascript for popup windows
dynamically sized to image dimensions.

ASP Example: How to use ASPJPEG to create thumbnails
Click for free Highly recommended thumbnailer for which you don't need Server access (doesn't seem to work on Windows Server 2008)

ASPjpeg: How to re-scale aspect ratio of thumbnails by height instead of width.

ASP Example: What if your host has an older version of ASPJPEG that doesn't support gifs?

Select Count Distinct Records for Access Database

Upload Image to folder and insert filename into database

Get date in such a way that it can be made part of a file name

Isolate a file name away from its path or extension or strip a path from a file name or strip characters from database field

User-customized on-the-fly stylesheet css files

Enhanced Page Hits Counter (also counts downloads and menu link hits)

Loop through array and compare to string with select case

Aphabetical Paging for your ASP scripts

Web Wiz Guide's Site Searcher Script modified as a file content indexer

Let Users Select How Many Records to View

Access Database for your PayPal IPN scripts

Miscellaneous collected code

From Classic ASP to PHP

You don't have to be a genius, just persistent, to write original Active Server Pages scripts

BuildApp - great old Classic ASP script generator!

Software Recommendation: bare_bones_no_bells_and_whistles_asp_code_generator_database_interface_maker (For PHP I recommend EasyGen.)

If any of this information is helpful to you, please consider donating with the button below. Thanks! ~~Lil