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)

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
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.
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...
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...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
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...
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.