Tek Eye Logo

Tek Eye

reCAPTCHA Code to Download for Demo and Test

The Tek Eye article Simple HTML Contact Form for PHP Based Website showed how to process HTML form data in a PHP form handler script. To prevent forms from being abused by bots some type of CAPTCHA is recommend. What is CAPTCHA? The term CAPTCHA is contrived from "Completely Automated Public Turing test to tell Computers and Humans Apart". A Turing Test is used to determine if a machine can realistically behave as a human. Therefore, CAPTCHA is a test to see if a human or a bot (robot software) is accessing a website. If the CAPTCHA test shows that a bot has probably filled in a HTML form, then the entered data can be rejected.

Use CAPTCHA to fool bots

Unfortunately, CAPTCHA solutions are not perfect due to the improvements in Artifical Intelligence (AI) software that is sometimes used to program bots. However, any CAPTCHA is better than nothing. Google reCAPTCHA is very popular, and there is hCAPTCHA, which is used to help identify objects and can generate some revenue for your website. This article provides some code as a demo of reCAPTCHA (currently at v3). The reCAPTCHA demo code in this article can be used to test a CAPTCHA solution for a HTML form submission.

Note: For reCAPTCHA calls of more than 1000 per second, or 1 million per month, you will need to use the reCAPTCHA Enterprise version.

How does reCAPTCHA work?

The Google reCAPTCHA code is added to a HTML form web page via a link to Google's reCAPTCHA JavaScript file. When the form is submitted a reCAPTCHA token is provided. The PHP script handling the form sends the reCAPTCHA token to Google's reCAPTCHA server. The Google reCAPTCHA server returns a score between 0.0 and 1.0, the closer to 1.0 the more likley the HTML form was submitted by a human. Your website can chose the level of the score to accept. A starting score of 0.5 is usual. If your website is getting to many false form submissions then you can raise the score closer to 1.0, before accepting the HTML submission data.

How does reCAPTCHA work

There is a web page for Google's own reCAPTCHA demonstration.

Register You Website with reCAPTCHA to Get Access Key

You will need a Google account to use reCAPTCHA. Go to the reCAPTCHA registration website and register a new site to use reCAPTCHA. One domain (e.g. example.com) and any of its sub-domains (e.g. subsite.example.com) is one site for registration purposes.

Once a site is registered for reCAPTCHA it will have two keys consisting of a long string of 40 characters and numbers:

  • Site Key: Used by the reCAPTCHA JavaScript in the web page that is sent to the website visitor.
  • Secret Key: Passed from the webserver to the reCAPTCHA server after a web page is submitted and the data needs to be checked for bot submissions.

The keys can be viewed for each website via the reCAPTCHA Admin Console, accessed via the gears icon for each registered website.

Adding reCAPTCHA JavaScript to a Web Page

The reCAPTCHA JavaScript is added to a web page using a HTML script tag within the head tag. In this tutorial the simple HTML form for the Tek Eye article Simple HTML Contact Form for PHP Based Website is used as the starting point. Here is the line of HTML code used to add the reCAPTCHA script.

<script src="https://www.google.com/recaptcha/api.js" defer></script>

The reCAPTCHA JavaScript will load when the page is viewed.

Linking reCAPTCHA to the HTML Form

The form submission event is linked to reCAPTCHA. Firstly, by adding a function that reCAPTCHA can call when the form is submitted, since reCAPTCHA will intercept the normal form submit. This is to allow reCAPTCHA to produce the token that will be used to verify the submission at the web server. Here, the form is given the id of comment-form, used to bind the new submission function to the forms submit action:

<script>
    function submitForm() {
        document.getElementById("comment-form").submit();
     }
</script>

The HTML forms submit input element has reCAPTCHA attributes added:

  • The class attribute is set to g-recaptcha
  • The data-callback is set to the previously defined submitForm function
  • The data-sitekey attribute is set to the value of the site key

The submission input becomes (replacing YOUR_reCAPTCHA_SITE_KEY_GOES_HERE with your own registered site key):

<input type="submit" value="Send" class="g-recaptcha"
    data-sitekey="YOUR_reCAPTCHA_SITE_KEY_GOES_HERE" data-callback="submitForm">

The full HTML form, with the form element given the id of comment-form, is:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML Form Demo</title>      
        <script src="https://www.google.com/recaptcha/api.js" defer></script>
        <script>
            function submitForm() {
                document.getElementById("comment-form").submit();
            }
        </script>
    </head>
    <body>
        <h1>Send a comment or question...</h1>
        <form action="handle-form.php" method="post" id="comment-form">
            <div>
                <label style="width: 60px; display: inline-block;">Name:</label>
                <input type="text" name="name" maxlength="50" required="">
            </div>
            <div style="margin-top:1em;">
                <label style="width: 60px;">Message:</label>
                <textarea style="vertical-align: top;" name="message"
                          cols="70" rows="4"
                          maxlength="1000" required=""></textarea>
            </div>
            <input type="submit" value="Send" class="g-recaptcha"
                data-sitekey="YOUR_reCAPTCHA_SITE_KEY_GOES_HERE" data-callback="submitForm">
        </form>
    </body>
</html>

The form appears the same as before when running in a browser.

HTML Contact Form

reCAPTCHA Verification of the Submission in the PHP Form Handler

When the HTML form is submitted a reCAPTCHA token is in the g-recaptcha-response POST data:

if (isset($_POST['g-recaptcha-response'])) {
    $captcha = $_POST['g-recaptcha-response'];
} else {
    $captcha = false;
}

The token, if present, is sent to the reCAPTCHA servers together with the secret key and the website ip address. Replace YOUR_reCAPTCHA_SECRET_KEY_GOES_HERE with the secret key for your website (the secret key, NOT the site key):

$secret='YOUR_reCAPTCHA_SECRET_KEY_GOES_HERE';
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".
    $secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);

The response from the reCAPTCHA server is decoded for a success flag (true or false) and a score (0.0 to 1.0), as well as a timestamp (challenge_ts) and a hostname. These can be checked to validate the submitted data from the HTML form. Here is the modified PHP form handler for this example, it includes error handling:

<head>
    <meta charset="utf-8" />
    <title>HTML Form Demo</title>
</head>
<body>
    <p>Processing feedback...</p>
    <?php 
        //Set an error message
        $submission_error = "Sorry, a submission error occurred: ";
        //Check for reCAPTCHA token
        if (isset($_POST['g-recaptcha-response'])) {
            $captcha = $_POST['g-recaptcha-response'];
        } else {
            $captcha = false;
        }
        //If no reCAPTCA token, show an error, otherwise verify data.
        if (!$captcha) {
            //Do something with no reCAPTCHA available
             echo "<p>".$submission_error." No verification data.</p>";
        } else {
            $secret='YOUR_reCAPTCHA_SECRET_KEY_GOES_HERE';
            $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".
                $secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
            // Use json_decode to extract json response
            $response = json_decode($response);
            //See if verification failed
            if ($response->success===false) {
                //Do something with failure
                echo "<p>".$submission_error." Data verification failed.</p>";
            } else {
                //If the reCAPTCHA is valid use the data
                //Otherwise filter out bad submissions
                //Change acceptable score as required
                if ($response->score <= 0.5) {
                    //Do something to deny access
                     echo "<p>".$submission_error." Data check failed.</p>";
                } else {
                    if(isset($_POST['name']))
                        echo "<p>Welcome ".$_POST['name']."</p>";
                    if(isset($_POST['message']))
                        echo "<p>Your message is: ".$_POST['message']."</p>";
                }
            }
        }
    ?>
 </body>

If the submission is normal then the result is the data being displayed:

HTML Form Data

Here is a print_r for an example reCAPTCHA response:

stdClass Object ( [success] => 1 [challenge_ts] => 2020-04-26T21:18:14Z [hostname] => example.com [score] => 0.9 )

This simple reCAPTCHA tutorial can be used as the basis for other HTML form submission verifications.

See Also

Author:  Published:  

ShareSubmit to TwitterSubmit to FacebookSubmit to LinkedInSubmit to redditPrint Page

markdown CMS Small Logo Icon ↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.


Articles on:

Android Programming and Android Practice Projects, HTML, VPS, Computing, IT, Computer History, ↓markdown↓ CMS, C# Programming, Using Windows for Programming


Free Android Projects and Samples:

Android Examples, Android List Examples, Android UI Examples



Maintain your PC with Piriform

Shop at Tek Eye for PC utilities