Count Active Users On Your
Web Site
By Pablo Varando
Have you ever wanted to display a count of how
many people are on your web site at any given moment? This tutorial will
demonstrate to you how to achieve just that. It will count your web site's
active sessions and allow you to display them to your visitors.
The first thing we need to do is check the Application.UsersInfo Structure to
see if it already
exists or else lets create it. This is achieved in the "Application.cfm"
after your <cfapplication>
tag.
<cflock timeout="15"
scope="APPLICATION"
type="EXCLUSIVE">
<cfif NOT isDefined("Application.UsersInfo")>
<cfset
Application.UsersInfo = StructNew()>
</cfif>
</cflock>
Ok now we need an unique variable to so we can
reference the Structure for this particular user,
so I'm going to use cfid, you can use the IP or anything you like but try to
make unique.
<cflock name="#CreateUUID()#"
timeout="15"
type="EXCLUSIVE">
<cfset user_cfid = Evaluate(CFID)>
<cfset user_time = Now()>
</cflock>
Ok now let's check if the user its already
counted or if it exists on the structure, this is why we
need an unique ID, else let's add it, we have a new users online.
<cflock scope="APPLICATION"
type="EXCLUSIVE"
timeout="15">
<cfif NOT StructKeyExists(Application.UsersInfo, user_cfid)>
<cfset temp = StructInsert(Application.UsersInfo, user_cfid, user_time)>
</cfif>
</cflock>
Ok now, we have to create a way to delete them
so they don't stay in the list forever, I'm
going to use a 10 minutes difference, to expire the user, remember this code
should be in
your application.cfm or included in your application.cfm, we are going to use
the DateDiff to
find out if the structure should be deleted.
<cflock scope="APPLICATION"
type="EXCLUSIVE" timeout="15">
<cfloop collection="#Application.UsersInfo#"
item="itmUser">
<cfif
Evaluate(DateDiff("n",
StructFind(Application.UsersInfo, itmUser), Now())) GT 10
>
<cfset StructDelete(Application.UsersInfo, itmUser)>
</cfif>
</cfloop>
</cflock>
Please note the the GT 10 can be any
value you choose. Simply make is any number and that is the lenght back it will
go to retrieve users using the application. Next let me show you how to count
the structure to get the display value for the web site.
Create the the page that displays the users
count: Call is "users_count.cfm".
Simply us this piece of code where you want to show how many users are currently
connected to your website.
<cflock scope="APPLICATION"
type="EXCLUSIVE"
timeout="10">
<cfoutput>
Total
Active Sessions : #StructCount(Application.UsersInfo)#
</cfoutput>
</cflock>
Now wherever you want to display the count,
simply include the file as follows:
<cfinclude template="users_count.cfm">
That's it, you have now counted visitors
sessions and are able to display them to the visitors of your site.