1
votes

Say I have the following script on page.cfm. Everytime somebody comes to page.cfm, an e-mail is sent to me. So if 1000 people come to page.cfm, I get 1000 e-mails.

<cfmail to="[email protected]"
from="[email protected]"
subject="Error"
type="text">
A person visited.
</cfmail>

I would like to limit it so I only get e-mails when the first 5 people visit in one day.

So if 2 people visit today, I get 2 e-mails. if 5 people visit I get 5, but if 100 people visit, I still get only 5 e-mails. And then the cycle continues the next day (if 2 people visit only 2 e-mails are send, but if 100 people visit only 5 e-mails are sent)

How can I do this with ColdFusion only? (without cfschedule)

3
Why not just set up Google Analytics? And check every online every once and awhile. Seems the emails will be a nuisance if you're not doing anything with them? - Merle_the_Pearl

3 Answers

7
votes

The simplest way I can think of is to put a counter and a date stamp in a pair of Application variables.

Then, for each request, check the date you've recorded. If it's not today, reset the counter variable to 1 and re-set the date to today.

Then, where you're putting the cfmail tag, do a check to see if the counter has reached your limit. If not, send the mail. Either way, increment the counter.

In Application.cfc onApplicationStart():

<cfset application.alertDate = now()>
<cfset application.alertCount = 1>

(the above is mostly to ensure that the variables exist when used later)

In Application.cfc onRequestStart():

<cfif dateCompare(application.alertDate,now(),"d") EQ -1)>
  <cfset application.alertCount = 1>
  <cfset application.alertDate = now()>
</cfif>

In page.cfm:

<cfset application.alertCount++>
<cfif application.alertCount LTE 5>
  <cfmail ... >
</cfif>
2
votes

Store the visit/email count in the Application scope, and reset the application scope every day by either

  1. store the last visitor date in the application scope as well, and add some logic to reset the count, or

  2. use cfscheduler to reset the count to 0 every day

0
votes

Late to the party, and I can't comment on previous answers just yet, so I'll do it this way. Both of the answers given will work, but you do need to know that those Application scope variables will disappear and reinitialize should your application end. If it's important to you, you will want to persist the values somewhere, something like an INI file accessed with getProfileString/setProfileString would work, or a table in a database.