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
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
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...
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
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 ...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...