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.

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)

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.

IoT & Smart Cities Stories
@CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
Rodrigo Coutinho is part of OutSystems' founders' team and currently the Head of Product Design. He provides a cross-functional role where he supports Product Management in defining the positioning and direction of the Agile Platform, while at the same time promoting model-based development and new techniques to deliver applications in the cloud.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. 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 settl...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...