Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Stopping Spam in Its Tracks . . .

. . . using CAPTCHA

Spammers come in many forms - e-mail spammers, search engine spammers, comment spammers, trackback spammers, message board spammers...

It seems as if there is no activity that can be done via the Internet that the lowly spammer is unwilling to intrude upon. Since spamming is a basically a numbers game, spammers spend a lot of time and effort automating the process of getting their spam to the widest possible audience. Using a CAPTCHA (Completely Automated Public Turing Test to tell Computers and humans apart) can go a long way toward preventing these automated spam attacks on your site.

In April I wrote a post on how you could easily add Peter Farrell's open source LylaCAPTCHA to Ray Camden's BlogCFC to prevent comment spam (www.remotesynthesis.com/blog/index.cfm/2006/4/24/Adding-OpenSource-LylaCaptcha-to-BlogCFC) and that very simple code ended up being rolled into the recently released BlogCFC v5. In this article, I want to expand upon that concept to show you not only how to integrate LylaCAPTCHA into any form, but also cover how we can use Rob Gonda's ajaxCFC to process the validation before the form is ever submitted.

Getting Started
Obviously the first thing you will need to do is download the appropriate project code from their respective sites. For the purposes of this example, all of my test code is within a folder called "captcha" directly under my site root. If you choose a different location, please be sure to adjust your paths appropriately throughout the example code. (The source code for this article.)

You can download the latest version of LylaCAPTCHA from http://lyla.maestropublishing.com/. The project code consists of two components and an XML configuration file, all of which I have placed within a subfolder called "lylacaptcha" within the example directory discussed previously. The only required change to the configuration XML that you will need is to modify the outputDirectory, which I have set to * for the purposes of our test (i.e., the current directory - to our root example files directory). This configuration tells LylaCAPTCHA where to store the generated images, which will be deleted as soon as they are done displaying anyway. LylaCAPTCHA offers a large set of configuration options that you can also adjust if you choose - just be sure to refer to the provided documentation first. Last, as of the writing of this article, LylaCAPTCHA was at version 0.2Alpha and there was a known bug regarding the setColor method, which you will need to complete the quick fix listed under "Known Bugs or Problems" on the LylaCAPTCHA site.

Next, you'll need to download ajaxCFC, which can be done at www.robgonda.com/blog/projects/ajaxcfc/. I copied the necessary content into a subfolder of our examples directory named "ajaxcfc". The content you'll require includes the two ColdFusion components and the "js" directory that contains a set of six JavaScripts. No further configuration is necessary at this point for ajaxCFC.

Building the Form
In this example, we'll be building an extremely simple form that collects a user's comments and summarily ignores them (sound like any sites you know?). What our form does care about is that you got the CAPTCHA correct, and it verifies this before the form is ever allowed to submit. First things first, let's get our application.cfm out of the way. The application file simply contains our cfapplication tag and our LylaCAPTCHA configuration code that should run only once when the application is initially configured. Obviously, if you are integrating this into your existing application, you simply need to incorporate lines 5 and 6 into your existing application startup code. Essentially, all you need to do is initialize LylaCAPTCHA with the XML file we edited above.

You can see the initialization code necessary for ajaxCFC on lines 17 through 22 of index.cfm. The first portion sets the appropriate component location, in this case ajaxCFC/ajaxCaptcha.cfc, which we'll discuss later, and the location of the JavaScript folder discussed in "Getting Started" above.

Overlooking the JavaScript for the moment, let's look at the form code on lines 49 through 57. There is nothing special to this form, except that there is a hidden form field that passes the hash necessary to decode the CAPTCHA response. We generate this hash per request on line 13 of index.cfm. It's important to note that the CAPTCHA image is actually referencing a cfm file and passing along the hash. The cfm file (showCaptcha.cfm) has only two lines of code. The first line generates the CAPTCHA image from the hash code we just passed, and the second serves this image up via a cfcontent tag that also takes care of removing the file for us as well.

Notice that I have overridden the standard form submission by adding onsubmit="return false;" to the form tag. This is because I call validateCaptcha() when the submit button is clicked, which will use ajaxCFC to verify that you have entered the correct CAPTCHA text by passing the value of the CAPTCHA text and hash form fields. Now let's take a look at the JavaScript necessary to perform the validation. Line 26 of index.cfm performs the ajaxCFC function call, which is invoking the validateCaptcha method on the CFC we defined in the initialization discussed previously (i.e., ajaxCFC/ajaxCaptcha.cfc). It also indicates that when the data is returned from the server, the captchaValidated JavaScript function should be called. Finally, we pass the validateCaptcha ColdFusion function the necessary CAPTCHA text and hash values.

Taking a look at the validateCaptcha function within ajaxCaptcha.cfc (lines 2-10), you'll see that all it does is pass back the value LylaCAPTCHA's validateCaptcha function, which is a boolean. When this value is returned, the captchaValidated JavaScript function is called and passed the result (index.cfm lines 29-36). All captchaValidated does is alert the user if the test was failed or submit the form if the test was passed. Note that on lines 1-11 of index.cfm, I include some dummy form processing code, which does however re-validate the CAPTCHA response in case someone figures out a way to bypass our script. This probably isn't completely necessary, but is simple to do and a good precaution.

Additional Functionality
Essentially, the code discussed above is all that is required. However, anyone who has encountered CAPTCHA knows that sometimes a particular CAPTCHA image may be extraordinarily difficult to read. Even the best CAPTCHA will be difficult to read a small percentage of the time. Well, we could refresh the page and get a new image, but then I might lose what I have typed, plus that seems counterintuitive. Wouldn't it be nice if we could just serve up a new image at the user's request? Well, we can't, so stop asking...wait, scratch that, we can.

What you need in order to generate a new image is a new hash code. We can expand our ajaxCaptcha.cfc with a function that will return a new hash code with all of three lines. The newCaptcha JavaScript function (index.cfm lines 38-40) calls the getNewCaptchaHash ColdFusion function (ajaxCaptcha.cfc lines 12-14), which takes no arguments and simply returns a new CAPTCHA hash reference. When the result is returned, the showNewCaptcha JavaScript function is called, which first sets the CAPTCHA image source to the new CAPTCHA image, and then changes the hidden form field hash reference value. Easy right?...and you said it couldn't be done.

Conclusion
I think at this point it should be obvious how easy it is to integrate either LylaCAPTCHA and ajaxCFC. Obviously, both projects can serve more purposes than we have covered here, and I recommend you check them out in greater detail. When you're wondering whatever happened to the treasurer of the Nigerian government, take a moment to thank the efforts of Peter Farrell and Rob Gonda for not only making superb products, but being generous enough to make them available to the rest of us free and open source. Last, if you are looking for other free and open source ColdFusion projects, check out my ColdFusion open source project list at www.remotesynthesis.com/cfopensourcelist.

More Stories By Brian Rinaldi

Brian Rinaldi, a member of the Editorial Board of CFDJ, is a web developer at Hasbro. He is also a member of the Adobe Community Experts program, the manager of the Boston ColdFusion User Group and an Advanced Certified ColdFusion MX Developer, as well as a Microsoft Certified Professional. Brian is most well known for his efforts promoting open-source projects in ColdFusion, especially for maintaining the ColdFusion open-source list as well as the weekly updates, both of which you can find via his web site at remotesynthesis.com.

Comments (5) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
CFDJ News Desk 07/20/06 12:53:33 PM EDT

Spammers come in many forms - e-mail spammers, search engine spammers, comment spammers, trackback spammers, message board spammers...

CFDJ News Desk 07/20/06 11:53:15 AM EDT

Spammers come in many forms - e-mail spammers, search engine spammers, comment spammers, trackback spammers, message board spammers...

Phil Robertson 07/18/06 01:29:06 PM EDT

You know what really burns me? When a web page article puts one of those floating windows up. What's worse is when the damn thing has a "Close Window" text that isn't enabled and clicking anywhere takes you to the advertisement you don't want anyway. So, did I read your article - NO, could I read your article - No.

!!!!!!!!!!!!!!!!!!!!!!!!!!!! Pissed!!!

Balbowa Rocky 07/14/06 02:00:06 AM EDT

Nice article Brain,

Even I do think that spam be it anywhere in blogs, forums and search results and e-mail, needs to be dealt seroiusly. All it is doing is simply creating nuisance. Like you, a site organicspam.com has put a step forth to dealt with spam in organic results in search results.
Great going guys. You people seriously put in a lot of efforts for the others sake. Hats Off to you.

SYS-CON Australia News Desk 06/28/06 11:56:00 AM EDT

Spammers come in many forms - e-mail spammers, search engine spammers, comment spammers, trackback spammers, message board spammers...

IoT & Smart Cities Stories
Early Bird Registration Discount Expires on August 31, 2018 Conference Registration Link ▸ HERE. Pick from all 200 sessions in all 10 tracks, plus 22 Keynotes & General Sessions! Lunch is served two days. EXPIRES AUGUST 31, 2018. Ticket prices: ($1,295-Aug 31) ($1,495-Oct 31) ($1,995-Nov 12) ($2,500-Walk-in)
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...