Overview

From reCAPTCHA Wiki

Jump to: navigation, search

reCAPTCHA is a free CAPTCHA service that helps protect your site against spam, malicious registrations and other forms of attacks where computers try to disguise themselves as a human; a CAPTCHA is a Completely Automated Public Turing test to tell Computers and Human Apart. ReCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration, etc. Below you can find instructions on how to add reCAPTCHA to your site.

Contents

Part 1: Sign Up

First, you’ll need to sign up at reCAPTCHA.net and create reCAPTCHA keys for your site.

The keys are unique to your domain and sub-domains and will not work for other domains unless you:

  • Sign up for multiple keys (one for each site)
  • Create a global key by checking the box for “Enable this key on all domains (global key)”

For example:

  • The keys for test.com will work on a.test.com, b.test.com, c.test.com and any other sub-domains
  • If the option “Enable this key on all domains (global key)” is checked, the keys will work on a.test.com, x.com, y.com and any other domain and sub-domains

Part 2: Installation

Installation consists of two steps and optionally a third step where you customize the widget:

  1. Client Side: Displaying the reCAPTCHA Widget (Required)
  2. Server Side: Verifying the solution (Required)
  3. Customizations (Optional)

In most Web forms, you usually have two files: the form itself with the fields and the file with the script to process the inputs to the form. These two files correspond to steps 1 and 2 above. Therefore, in most cases you will have to modify two different files.

Displaying the reCAPTCHA widget is the simpler step. You can usually display it using an application plugin (recommended; see below), or alternatively by adding the javascript below inside your <form> element (a third option discussed later is to use the AJAX API):

 
  <script type="text/javascript"
    src="http://api.recaptcha.net/challenge?k=your_public_key">
  </script>
  <noscript>
    <iframe src="http://api.recaptcha.net/noscript?k=your_public_key"
        height="300" width="500" frameborder="0"></iframe><br>
    
  </noscript>
  

It probably goes without saying, but we'll say it anyway: you need to replace the two instances of your_public_key with the public key that you received during the account creation process (Part 1 above). Be careful that you don't use your private key by mistake.

Verifying the solution is a bit more difficult, and usually requires modifying a script. If you’re using one of the following programming environments or applications, use these resources and instructions:

Programming Environments:

Applications:

Otherwise:

  • DIY Installation (requires you to write code to communicate with our servers to verify the solution)

PHP

Download the reCAPTCHA PHP library. You will only need one file from there (recaptchalib.php). The other files are examples, readme and legal stuff -- they don’t affect functionality.

Client Side (How to make the CAPTCHA image show up)

If you want to use the PHP library to display the reCAPTCHA widget, you'll need to insert this snippet of code inside the <form> element where the reCAPTCHA widget will be placed:

 require_once('recaptchalib.php');
 $publickey = "your_public_key"; // you got this from the signup page
 echo recaptcha_get_html($publickey);

With the code, your form might look something like this:

 <!-- your HTML content -->
<form method="post" action="verify.php"> <?php require_once('recaptchalib.php'); $publickey = "your_public_key"; // you got this from the signup page echo recaptcha_get_html($publickey);  ?> <input type="submit" /> </form>
<!-- more of your HTML content -->

Don't forget to set $publickey by replacing your_public_key with the value you obtained in Part 1 above.

Note that the value of the "action" attribute is "verify.php". Now, verify.php is the destination file in which the values of this form are submitted to. So you will need a file verify.php in the same location as the client html.

The require_once function in the example above expects recaptchalib.php to be in the same directory as your form file. If it is in another directory, you must link it appropriately. For example if your recaptchalib.php is in the directory called “captcha” that is on the same level as your form file, the function will look like this: require_once('captcha/recaptchalib.php').

Also make sure your form is set to get the form variables using $_POST, instead of $_REQUEST, and that the form itself is using the POST method.

Server Side (How to test if the user entered the right answer)

The following code should be placed at the top of the verify.php file:

 <?php
 require_once('recaptchalib.php');
 $privatekey = "your_private_key";
 $resp = recaptcha_check_answer ($privatekey,
                               $_SERVER["REMOTE_ADDR"],
                               $_POST["recaptcha_challenge_field"],
                               $_POST["recaptcha_response_field"]);
if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")"); } else { // Your code here to handle a successful verification }  ?>

In the code above:

  • recaptcha_check_answer returns an object that represents whether the user successfully completed the challenge.
  • If $resp->is_valid is true then the captcha challenge was correctly completed and you should continue with form processing.
  • If $resp->is_valid is false then the user failed to provide the correct captcha text and you should redisplay the form to allow them another attempt. In this case $resp->error will be an error code that can be provided to recaptcha_get_html. Passing the error code makes the reCAPTCHA control display a message explaining that the user entered the text incorrectly and should try again.

Notice that this code is asking for the private key, which should not be confused with the public key. You get that from the same page as the public key.

That's it! reCAPTCHA should now be working on your site.

ASP.NET

  • Download the reCAPTCHA ASP.NET library.
  • Add a reference on your website to library/bin/Release/Recaptcha.dll: On the Visual Studio Website menu, choose Add Reference and then click the .NET tab in the dialog box. Select the Recaptcha.dll component from the list of .NET components and then click OK. If you don't see the component, click the Browse tab and look for the assembly file on your hard drive.
  • Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:

At the top of the aspx page, insert this:

 <%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

Then insert the reCAPTCHA control inside of the <form runat="server"> tag:

 <recaptcha:RecaptchaControl
   ID="recaptcha"
   runat="server"
   PublicKey="your_public_key"            
   PrivateKey="your_private_key"
   />
  • You will need to substitute your public and private key into PublicKey and PrivateKey respectively.
  • Make sure you use ASP.NET validation to validate your form (you should check Page.IsValid on submission).
  • The following is a "Hello World" with reCAPTCHA using Visual Basic. A C# sample is included with the library download:
 <%@ Page Language="VB" %>
 <%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>
 <script runat=server>
     Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
         If Page.IsValid Then
             lblResult.Text = "You Got It!"
             lblResult.ForeColor = Drawing.Color.Green
         Else
             lblResult.Text = "Incorrect"
             lblResult.ForeColor = Drawing.Color.Red
         End If
     End Sub
 </script>
 <html>
 <body>
     <form runat="server">
         <asp:Label Visible=false ID="lblResult" runat="server" />   
         <recaptcha:RecaptchaControl
             ID="recaptcha"
             runat="server"
             Theme="red"
             PublicKey="your_public_key"            
             PrivateKey="your_private_key"
             />
         <br />
         <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
     </form>
 </body>
 </html>


Classic ASP

  • Put this code at the top of your ASP page:
 <%
 recaptcha_challenge_field  = Request("recaptcha_challenge_field")
 recaptcha_response_field   = Request("recaptcha_response_field")
 recaptcha_public_key       = "your_public_key" ' your public key
 recaptcha_private_key      = "your_private_key" ' your private key
' returns the HTML for the widget function recaptcha_challenge_writer()
recaptcha_challenge_writer = _ "<script type=""text/javascript"">" & _ "var RecaptchaOptions = {" & _ " theme : 'red'," & _ " tabindex : 0" & _ "};" & _ "</script>" & _ "<script type=""text/javascript"" src=""http://api.recaptcha.net/challenge?k=" & recaptcha_public_key & """></script>" & _ "<noscript>" & _ "<iframe src=""http://api.recaptcha.net/noscript?k=" & recaptcha_public_key & """ frameborder=""1""></iframe><br>" & _ "<textarea name=""recaptcha_challenge_field"" rows=""3""cols=""40""></textarea>" & _ "<input type=""hidden"" name=""recaptcha_response_field""value=""manual_challenge"">" & _ "</noscript>"
end function
' returns "" if correct, otherwise it returns the error response function recaptcha_confirm(rechallenge,reresponse)
Dim VarString VarString = _ "privatekey=" & recaptcha_private_key & _ "&remoteip=" & Request.ServerVariables("REMOTE_ADDR") & _ "&challenge=" & rechallenge & _ "&response=" & reresponse
Dim objXmlHttp Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP") objXmlHttp.open "POST", "http://api-verify.recaptcha.net/verify", False objXmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" objXmlHttp.send VarString
Dim ResponseString ResponseString = split(objXmlHttp.responseText, vblf) Set objXmlHttp = Nothing
if ResponseString(0) = "true" then 'They answered correctly recaptcha_confirm = "" else 'They answered incorrectly recaptcha_confirm = ResponseString(1) end if
end function
server_response = "" newCaptcha = True if (recaptcha_challenge_field <> "" or recaptcha_response_field <> "") then server_response = recaptcha_confirm(recaptcha_challenge_field, recaptcha_response_field) newCaptcha = False end if
 %>

What happens here is the variables "server_response" and "newCaptcha" are set whenever the page is loaded, allowing you to determine the state of your page.

  • You can use the following HTML as a skeleton:
 <html>
 <body>
<% if server_response <> "" or newCaptcha then %>
<% if newCaptcha = False then %>
<!-- An error occurred --> Wrong!
<% end if %>
<!-- Generating the form --> <form action="recaptcha.asp" method="post"> <%=recaptcha_challenge_writer()%> </form>
<% else %>
<!-- The solution was correct --> Correct!
<%end if%>
</body> </html>


Java/JSP

Download the reCAPTCHA Java Library here (contributed by Soren) and unzip it. Typically the only thing you'll need is the jar file (recaptcha4j-X.X.X.jar), which you have to copy to a place where it can be loaded by your java application. For example, if you are using Tomcat to run JSP, you may put the jar file in a directory called WEB-INF/lib/.

Client Side (How to make the CAPTCHA image show up)

If you want to use the Java plugin to display the reCAPTCHA widget, you'll need to import the appropriate reCAPTCHA classes. In JSP, you would do this by inserting these lines near the top of the file with the form element where the reCAPTCHA widget will be displayed:

   <%@ page import="net.tanesha.recaptcha.ReCaptcha" %>
   <%@ page import="net.tanesha.recaptcha.ReCaptchaFactory" %>

Then, you need to create an instance of reCAPTCHA:

   ReCaptcha c = ReCaptchaFactory.newReCaptcha("your_public_key", "your_private_key", false);

Finally, the HTML to display the reCAPTCHA widget can be obtained from the following function call:

   c.createRecaptchaHtml(null, null)

So, in JSP your code may look something like this:

   <%@ page import="net.tanesha.recaptcha.ReCaptcha" %>
   <%@ page import="net.tanesha.recaptcha.ReCaptchaFactory" %>
<html> <body> <form action="" method="post"> <% ReCaptcha c = ReCaptchaFactory.newReCaptcha("your_public_key", "your_private_key", false); out.print(c.createRecaptchaHtml(null, null));  %> <input type="submit" value="submit" /> </form> </body> </html>

Don't forget to replace your_public_key and your_private_key with the values you obtained in Part 1 above.

Server Side (How to test if the user entered the right answer)

In the application that verifies your form, you'll first need to import the necessary reCAPTCHA classes:

   import net.tanesha.recaptcha.ReCaptchaImpl;
   import net.tanesha.recaptcha.ReCaptchaResponse;

Next, you need to insert the code that verifies the reCAPTCHA solution entered by the user. The example below (in JSP) shows how this can be done:

   <%@ page import="net.tanesha.recaptcha.ReCaptchaImpl" %>
   <%@ page import="net.tanesha.recaptcha.ReCaptchaResponse" %>
<html> <body> <% String remoteAddr = request.getRemoteAddr(); ReCaptchaImpl reCaptcha = new ReCaptchaImpl(); reCaptcha.setPrivateKey("your_private_key");
String challenge = request.getParameter("recaptcha_challenge_field"); String uresponse = request.getParameter("recaptcha_response_field"); ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
if (reCaptchaResponse.isValid()) { out.print("Answer was entered correctly!"); } else { out.print("Answer is wrong"); }  %> </body> </html>

In the code above:

  • remoteAddr is the user's IP address (which is passed to the reCAPTCHA servers)
  • uresponse contains the user's answer to the reCAPTCHA challenge.

If you're having trouble, you can also see the following article that explains how to add reCAPTCHA to your Java application: How to reCAPTCHA Your Java Application

Important: DNS Caching

Java has an annoying issue that may cause the connection between your server and reCAPTCHA to be interrupted every few months, and reCAPTCHA will stop working in your site when that happens. Read below to see how to fix this.

By default the Java Virtual Machine (JVM) caches all DNS lookups forever instead of using the time-to-live (TTL) value which is specified in the DNS record of each host. For those of you how do not know it, a DNS lookup is a request sent to a DNS server which converts a readable hostname to an IP address. For example, it converts www.recaptcha.net to the IP address 69.12.97.164. It is of course much more complex than this, and if you want to learn more, wikipedia's entry on DNS is a good starting point.

Although not frequently, reCAPTCHA servers can change IP addresses. Because Java caches DNS lookups forever, this can cause the connection between your server and reCAPTCHA to go down when the reCAPTCHA IP address changes. If this happens, restarting your JVM (e.g., restarting Tomcat) can fix the problem because it causes a new DNS lookup. However, you probably don't want to restart your JVM once every few months whenever your site breaks because the reCAPTCHA servers changed IP address.

To fix this issue for good, you can pass -Dsun.net.inetaddr.ttl=30 to your app-server (this tells Java to only cache DNS for 30 seconds). In Tomcat for Windows, this can be done by following the steps below:

1. Stop Tomcat
2. Go to tomcat\bin
3. Run Tomcat5w.exe
4. Goto java tab
5. Add java property to java options section: -Dsun.net.inetaddr.ttl=30
6. Exit
7. Start Tomcat

In Tomcat for Linux or MacOS X, you need to run the following command in the command line and restart Tomcat:

   export JAVA_OPTS="$JAVA_OPTS -Dsun.net.inetaddr.ttl=30"

Here is an article explaining more about this issue.

Perl

Download the reCAPTCHA Perl Module (contributed by Andy Armstrong). You will need to install this module on your machine (web server). The module depends on the modules LWP::UserAgent and HTML::Tiny, both of which will also need to be installed. Here are some basic instructions on installing Perl modules.

Client Side (How to make the CAPTCHA image show up)

If you want to use the Perl library to display the reCAPTCHA widget, you'll need to insert this line near the top of the file with the form element where the reCAPTCHA widget will be displayed:

   use Captcha::reCAPTCHA;

Then, you need to create an instance of reCAPTCHA:

   my $c = Captcha::reCAPTCHA->new;

Finally, to display the reCAPTCHA widget, you must place the following line inside the <form> tag:

   print $c->get_html("your_public_key");

So, your code may look something like this:

   use Captcha::reCAPTCHA;
my $c = Captcha::reCAPTCHA->new;
print <<EOT; <html> <body> <form action="" method="post"> EOT
print $c->get_html("your_public_key");
print <<EOT; <input type="submit" value="submit" /> </form> </body> </html> EOT

Don't forget to replace your_public_key with the value you obtained in Part 1 above.

Server Side (How to test if the user entered the right answer)

Below is a skeleton of how to verify the reCAPTCHA answer:

   use Captcha::reCAPTCHA;
my $c = Captcha::reCAPTCHA->new;
my $challenge = the value of param 'recaptcha_challenge_field'; my $response = the value of param 'recaptcha_response_field';
# Verify submission my $result = $c->check_answer( "your_private_key", $ENV{'REMOTE_ADDR'}, $challenge, $response );
if ( $result->{is_valid} ) { print "Yes!"; } else { # Error print "No"; }

FormMail

Here we will explain how to add reCAPTCHA to your FormMail script without using the reCAPTCHA Perl Module. If you know what you're doing, you can alternatively use the reCAPTCHA Perl Module.

Client Side (How to make the CAPTCHA image show up)

In your HTML page, inside the <form> element you must add the following code:

 
  <script type="text/javascript"
    src="http://api.recaptcha.net/challenge?k=your_public_key">
  </script>
  <noscript>
    <iframe src="http://api.recaptcha.net/noscript?k=your_public_key"
        height="300" width="500" frameborder="0"></iframe><br>
    <textarea name="recaptcha_challenge_field" rows="3" cols="40">
    </textarea>
    <input type="hidden" name="recaptcha_response_field" 
        value="manual_challenge">
  </noscript>
  

It probably goes without saying, but we'll say it anyway: you need to replace the two instances of your_public_key with the public key that you received during the account creation process (Part 1 above). Be careful that you don't use your private key by mistake.

This will basically add two parameters, which are passed to formmail.cgi (or FormMail.pl) through a POST request, namely:

recaptcha_challenge_field
This is the challenge created through your public key.
recaptcha_response_field
This is the user-submitted response to the challenge above.

Server Side (How to test if the user entered the right answer)

Next, you need to modify formmail.cgi (or FormMail.pl) to handle the two parameters and to validate the challenge from the reCAPTCHA servers. At this point, it's probably a good idea to make a backup copy of your FormMail.pl, just in case. In the code below, "+" means the line needs to be added to the FormMail script, and "-" means the line needs to be removed from it. In every case, we show where the lines need to be added or removed by showing the adjacent lines in the FormMail script.

First, you need to tell Perl to use the module LWP::UserAgent by adding the following line to FormMail:

# ACCESS CONTROL FIX: Peter D. Thompson Yezek                                #
#                     http://www.securityfocus.com/archive/1/62033           #
##############################################################################
+use LWP::UserAgent;
+

(This will require the module LWP::UserAgent to be in your Perl environment. Most installations of Perl already have this module. In case the module is not installed, here are some basic instructions on installing Perl modules.)

Then, add code to call the CAPTCHA check functionality defined below.

# Check Required Fields
&check_required;
 
+# Check the captcha challenge and response.
+&check_captcha;
+
# Send E-Mail
&send_mail;

# Return HTML Page or Redirect User
&return_html;

Now, validate the CAPTCHA response and generate an error if the response doesn't match the challenge.

+##############################################################################
+# Check the CAPTCHA response via the reCAPTCHA service.
+sub check_captcha {
+
+      my $ua = LWP::UserAgent->new();
+      my $result=$ua->post(
+      'http://api-verify.recaptcha.net/verify',
+      {
+          privatekey => 'your_private_key',
+          remoteip   => $ENV{'REMOTE_ADDR'},
+          challenge  => $Form{'recaptcha_challenge_field'},
+          response   => $Form{'recaptcha_response_field'}
+      });
+
+      if ( $result->is_success && $result->content =~ /^true/) {
+              return;
+      } else {
+              &error('captcha_failed');
+      }
+}
+
# NOTE rev1.91: This function is no longer intended to stop abuse, that      #
#    functionality is now embedded in the checks made on @recipients and the #
#    recipient form field.                                                   #

Finally, create the functionality that prints the error message in case the check fails:

        if ($Config{'missing_fields_redirect'}) {
            print "Location: " . &clean_html($Config{'missing_fields_redirect'}) . "\n\n";
        }
+    }
+    elsif ($error eq 'captcha_failed') {
+            print <<"(END ERROR HTML)";
+Content-type: text/html
+
+<html>
+ <head>
+  <title>Error: Captcha Check Failed</title>
+ </head>
+ <body bgcolor=#FFFFFF text=#000000>
+ <center>
+  <table border=0 width=600 bgcolor=#9C9C9C>
+    <tr><th>Error: Captcha Check Failed</th></tr>
+   </table>
+  <table border=0 width=600 bgcolor=#CFCFCF>
+    <tr><td>The Captcha response of the form you submitted did not match the challenge.
+     Please check the form and make sure that your response matches the challenge in the captcha image.
+     You can use the browser back button to return to the form.
+     </center>
+    </td></tr>
+   </table>
+  </center>
+ </body>
+</html>
+(END ERROR HTML)
+    }
        else {
             foreach $missing_field (@error_fields) {
           $missing_field_list .= "<li>" . &clean_html($missing_field) . "\n";
.
.
.
 </html>
(END ERROR HTML)
        }
-    }
-
    exit;
}

That's it! reCAPTCHA should now be working on your site.

DIY Installation: The reCAPTCHA API

Overview: How reCAPTCHA Works

File:recaptcha-api-diagram.gif

  1. The user loads the web page with the reCAPTCHA challenge JavaScript embedded.
  2. The user's browser requests a challenge from reCAPTCHA. reCAPTCHA gives the user a challenge and a token that identifies the challenge.
  3. The user fills out the web page form, and submits the result to your application server, along with the challenge token.
  4. reCAPTCHA checks the user's answer, and gives you back a response.
  5. If true, generally you will allow the user access to some service or information. E.g. allow them to comment on a forum, register for a wiki, or get access to an email address. If false, you can allow the user to try again.


Client Side (How to make the CAPTCHA image show up)

This part requires you to embed some code in your website. You can use either:

Challenge and Non-JavaScript API

You will need to insert this snippet of JavaScript & non-JavaScript code in your <form> element and replace your_public_key with your public key:

 <script type="text/javascript"
    src="http://api.recaptcha.net/challenge?k=your_public_key">
 </script>
 <noscript>
    <iframe src="http://api.recaptcha.net/noscript?k=your_public_key"
        height="300" width="500" frameborder="0"></iframe><br>
    <textarea name="recaptcha_challenge_field" rows="3" cols="40">
    </textarea>
    <input type="hidden" name="recaptcha_response_field" 
        value="manual_challenge">
 </noscript>

So it will look something like this:

 <!-- ... your HTML content ... -->
<form action="<link to file that processes this form and verifies the reCAPTCHA solution>" method="post">
<!-- ... your form code here ... -->
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=your_public_key"> </script> <noscript> <iframe src="http://api.recaptcha.net/noscript?k=your_public_key" height="300" width="500" frameborder="0"></iframe><br> <textarea name="recaptcha_challenge_field" rows="3" cols="40"> </textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"> </noscript>
<!-- ... more of your form code here ... -->
</form>
<!-- ... more of your HTML content ... -->

There are two form fields:

  • recaptcha_challenge_field is a hidden field that describes the CAPTCHA which the user is solving. It corresponds to the "challenge" parameter required by the reCAPTCHA verification API.
  • recaptcha_response_field is a text field where the user enters their solution. It corresponds to the "response" parameter required by the reCAPTCHA verification API

These two fields will be passed to the file on your server that processes this form and verifies the reCAPTCHA solution via the [reCAPTCHA verification API].

AJAX API

Alternatively you can use the reCAPTCHA AJAX API if you require the reCAPTCHA widget to show on the fly based on some kind of user input.

Firstly, you will need to insert this snippet of JavaScript in the <head> element of your HTML document:

 <script type="text/javascript" src="http://api.recaptcha.net/js/recaptcha_ajax.js"></script>

This JavaScript file defines an object called Recaptcha. The methods of the Recaptcha object are outlined here.

Secondly, you will need to create an empty <div> element with an id in your HTML document for which the reCAPTCHA object will be placed.

Now, in order to create the reCAPTCHA widget, you will need to call the Recaptcha object's create method in response to some user action and replace:

  • your_public_key with your public key
  • element_id with the id of the div element you reserved for the reCAPTCHA widget
 Recaptcha.create("your_public_key",
   "element_id", 
   {  
     theme: "red",
     callback: Recaptcha.focus_response_field 
   }
 );

Taking a closer look at the Recaptcha.create (public_key, element, options) method, there are 3 input parameters:

  • public_key: your public key
  • element: JavaScript Element object or the string ID of the element in your HTML document (we don't cover the JavaScript Element in this example)
  • options: JavaScript Dictionary with specific keys and values

Your HTML page should look something like this:

 <html>
<head>
<!-- ... your HTML <head> content ... -->
<script type="text/javascript" src="http://api.recaptcha.net/js/recaptcha_ajax.js"></script>
<!-- Wrapping the Recaptcha create method in a javascript function --> <script type="text/javascript"> function showRecaptcha(element) { Recaptcha.create("your_public_key", element, { theme: "red", callback: Recaptcha.focus_response_field}); } </script>
<!-- ... more of your HTML <head> content ... -->
</head>
<body>
<!-- ... your HTML <body> content ... -->
<div id="recaptcha_div"></div><nowiki><br> <input type="button" value="Show reCAPTCHA" onclick="showRecaptcha('recaptcha_div');"></input> <br><nowiki> <!-- ... more of your HTML <body> content ... -->
<body>
</html>

To verify the solution, you will need to pass two variables from the widget (along with a few other server side parameters) to the reCAPTCHA verification API. These variables can be accessed by the Recaptcha object's methods:

  • Recaptcha.get_challenge(): corresponds to the "challenge" parameter required by the reCAPTCHA verification API
  • Recaptcha.get_response(): corresponds to the "response" parameter required by the reCAPTCHA verification API


Server Side (How to test if the user entered the right answer)

API Request

URL: http://api-verify.recaptcha.net/verify

Parameters (sent via POST)
privatekey (required) Your private key
remoteip (required) The IP address of the user who solved the CAPTCHA.
challenge (required) The value of "recaptcha_challenge_field" sent via the form
response (required) The value of "recaptcha_response_field" sent via the form

API Response

The response from verify is a series of strings separated by \n. To read the string, split the line and read each field. New lines may be added in the future.

Line 1 "true" or "false". True if the reCAPTCHA was successful
Line 2 if Line 1 is false, then this string will be an error code.

reCAPTCHA can display the error to the user (through the error parameter of api.recaptcha.net/challenge). Implementations should not depend on error code names, as they may change in the future.

Example: If your response looks like this:

false incorrect-captcha-sol

... you can add '&error=incorrect-captcha-sol' to the challenge request URL, and the user will get an error code.

Part 3: Customizing Look and Feel

Now that you've successfully installed reCAPTCHA on your site, you may want to change the way it looks. There are two ways to do this: (1) choosing one of the standard reCAPTCHA themes, or (2) fully customizing the appearance of reCAPTCHA.

Standard Themes

The first step is to add the following code in your main HTML page anywhere before the <form> element where reCAPTCHA appears:

<script type="text/javascript">
var RecaptchaOptions = {
   theme : 'theme_name'
};
</script>

Note: This will not work if it appears after the main script where reCAPTCHA is first invoked.

To use a standard theme, you need to replace theme_name by one of the following four theme names:

  • 'red' (default theme)
  • 'white'

Image:Rcptacleanxk9.png

  • 'blackglass'

Image:Rcptablackglasslj0.png

  • 'clean'

Image:Rcptagraycz8.png

Custom Theming

To use a fully custom theme, you will need to tell reCAPTCHA that it should not create a user interface of its own. reCAPTCHA will rely on the presence of HTML elements with the following IDs to display the CAPTCHA to the user:

  • An empty div with ID recaptcha_image. This is where the actual image will be placed. The div will be automatically set to 300x57 pixels.
  • A text input with ID and name both set to recaptcha_response_field. This is where the user can enter their answer.
  • A div that contains the entire reCAPTCHA widget. The ID of this div should be placed into the parameter custom_theme_widget of RecaptchaOptions, and the style of the div should be set to display:none. After the reCAPTCHA theming code has fully loaded, it will make the div visible. This element avoids making the page flicker while it loads.

To implement all of this this, first place the following code in your main HTML page anywhere before the <form> element where reCAPTCHA appears:

<script type="text/javascript">
var RecaptchaOptions = {
   theme : 'custom',
   custom_theme_widget: 'recaptcha_widget'
};
</script>

Then, inside the <form> element where you want reCAPTCHA to appear, place:


 <div id="recaptcha_widget" style="display:none">

   <div id="recaptcha_image"></div>
   <div class="recaptcha_only_if_incorrect_sol" style="color:red">Incorrect please try again</div>

   <span class="recaptcha_only_if_image">Enter the words above:</span>
   <span class="recaptcha_only_if_audio">Enter the numbers you hear:</span>

   <input type="text" id="recaptcha_response_field" name="recaptcha_response_field" />

   <div><a href="javascript:Recaptcha.reload()">Get another CAPTCHA</a></div>
   <div class="recaptcha_only_if_image"><a href="javascript:Recaptcha.switch_type('audio')">Get an audio CAPTCHA</a></div>
   <div class="recaptcha_only_if_audio"><a href="javascript:Recaptcha.switch_type('image')">Get an image CAPTCHA</a></div>

   <div><a href="javascript:Recaptcha.showhelp()">Help</a>

 </div>

 <script type="text/javascript"
    src="http://api.recaptcha.net/challenge?k=your_public_key">
 </script>
 <noscript>
   <iframe src="http://api.recaptcha.net/noscript?k=your_public_key"
        height="300" width="500" frameborder="0"></iframe><br>
   <textarea name="recaptcha_challenge_field" rows="3" cols="40">
   </textarea>
   <input type="hidden" name="recaptcha_response_field"
        value="manual_challenge">
 </noscript>

Notice that the last few lines are simply the standard way to display reCAPTCHA explained at the beginning of this document.

Here's what's going on in the code above. The Recaptcha JavaScript object provides methods which allow you to change the state of the CAPTCHA. The method reload displays a new CAPTCHA challenge, and the method switch_type toggles between image and audio CAPTCHAs. In order to create a full UI for reCAPTCHA, we display different information when the CAPTCHA is in different states. For instance, when the user is viewing an image CAPTCHA, a link to "Get an audio CAPTCHA" is shown. Four CSS classes are available for you to create a stateful UI:

  • recaptcha_only_if_image, visible when an image CAPTCHA is being displayed
  • recaptcha_only_if_audio, visible when an audio CAPTCHA is being displayed
  • recaptcha_only_if_incorrect_sol, visible when the previous solution was incorrect
  • recaptcha_only_if_no_incorrect_sol, visible when the previous solution was not incorrect

While theming does give you many options, you need to follow some user interface consistency rules:

  • You must state that you are using reCAPTCHA near the CAPTCHA widget.
  • You must provide a visible button that calls the reload function.
  • You must provide a way for visually impaired users to access an audio CAPTCHA.
  • You must provide alt text for any images that you use as buttons in the reCAPTCHA widget.

Troubleshooting

I Can't Work Out Where to Add reCAPTCHA

This advice applies to everyone who's integrating reCAPTCHA -- irrespective of language.

Firstly you need to identify two hot spots in your code. These are the places where you'll be adding the reCAPTCHA calls.

Display reCAPTCHA

The first hot spot is the code that generates the form. Hopefully that's easy enough to find and you have been able to display the CAPTCHA on your form.

Check reCAPTCHA

The second hot spot is the one that seems to cause people problems. You need to identify the code that handles form submission -- that is the code that runs when the user clicks on submit. It's hard to generalize about what this code looks like but here are some clues that may help you:

  • if your form can ever display an error message, for example if a required field is blank, look for the code that generates that error message.
  • if your form places information in a database look for code that does a SQL INSERT.
  • if your form sends mail, search for the code that does that.

Form Already Has Validation

Life will be easier if your form already has some validation logic (i.e. it handles invalid input from the user by displaying a message instead of performing whatever action it normally would). If that's the case and you can find the code that does that you're nearly home free. If the form can display an error message search for the text of the error message within the code and you're sure to be close. Once you've found the validation code you need to add a call to the check_answer function in addition to whatever other checks are there (email address blank? age too young? etc.).

Form Has No Validation

If there's currently no validation logic for your form -- if clicking on submit *always* succeeds -- then you have a more tricky problem. In that case you'll have to add the reCAPTCHA validation code right before the existing form handling code does whatever it does when the user submits. You'll also have to figure out how to redisplay the form to give the user another attempt at the captcha. Unfortunately there's no one stock answer to how you do that. It depends entirely on the structure of the code you already have. If the existing code isn't too complex you may have luck posting it on the reCAPTCHA discussion group and asking for advice.

It's Not Working! Help!

Before doing anything else make sure you're using the correct keys. Are your public and private keys swapped? Did you remember to put the private key in the form handler as well as putting the public key in the form?

Note that Mailhide uses different keys from the main form-based reCAPTCHA.

Be sure that your form uses the POST method, or else change the reCAPTCHA form handler variables to GET instead of POST.

I Keep Getting "verify-params-incorrect" When Developing with Windows Vista

Vista defaults to IPV6 for localhost and the IP of the browser on localhost will be sent to ReCAPTCHA as "0:0:0:0:0:0:0:1". You must test for this and change it to "127.0.0.1" during development.

reCAPTCHA is Accepting Incorrect Words

One of the words displayed by reCAPTCHA is from an old book which is being digitized. As such it is not graded -- it cannot. Indeed, occasionally it may be blank, or just a bit of noise.

On the word that is checked, the user is (by default) allowed to be off by one letter. It has been found that this increases the user experience while not degrading security by a large amount. This is tuned dynamically based on many factors.

No, I Mean *Totally* Incorrect Words

You probably aren't validating the reCAPTCHA answer with the API servers.