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 (see step 1. in the image). The reCAPTCHA code is via a link to Google's reCAPTCHA JavaScript file (2.). When the HTML form is then submitted, a reCAPTCHA token is provided (3.). The PHP script handling the form sends the reCAPTCHA token to Google's reCAPTCHA server (4.). 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 (5.). 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. Your website can then decide to accept or reject the HTML submission data (6.).

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 shown here. This can be copied and saved to a HTML file on your website if you want to test it, otherwise use you own HTML form as required.

<!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 web server PHP form handler script can now send the reCAPTCHA response token (if successfully received) to Google's reCAPTCHA verification server, along with your website's secret key. Assign your site's secret key in the PHP script. 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';

In this tutorial the curl url request library is used to post the reCAPTCHA token and secret key to the Google verification server. Some solutions use the PHP file_get_contents function to send the token and secret to Google's servers. However, many recent PHP installations on web servers have an initialisation flag enabled that prevents this from working. However, curl is often turned on in web server PHP installations. Here is the curl code that will perform a HTTP post containing the query parameters for Google's reCAPTCHA verify web address. It returns an error in a JSON format if the HTTP post fails:

//Construct query paramters
$query_content = http_build_query(array('secret'=>$secret,'response'=>$captcha));
//Start curl
$curl=curl_init();
//Set options for cURL: url, return as value, do a post
curl_setopt($curl, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,$query_content);
//Do the post to Google servers
$response=curl_exec($curl);
//Close cURL resource, free up system resources
curl_close($curl);
//Check curl response
if ($response === false)
    //set error in JSON format
    $response='{"success": false, "error-codes": ["connection-failed"]}';

The response from the reCAPTCHA server is in JSON format. It 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. The success flag and score can be checked to validate the submitted data from the HTML form.

Here is the full PHP form handler for this example, it includes error handling and cleansing of the input data. It can be copied to a PHP file on your website for testing, or adapt your own PHP script as appropriate. To match with the full HTML form above, it should be saved as handle-form.php. Remember to change YOUR_reCAPTCHA_SECRET_KEY_GOES_HERE for your registered reCAPTCHA secret key (not your site key).

<!DOCTYPE html>
    <html lang="en">
    <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: ";
            // Define a filter function for data sanitization
            function clean_data($data) {
                // trim whitespace
                $data = trim($data);
                // reduce website manipulation via HTML tags
                $data = htmlspecialchars($data);
                return $data;
            }
            //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';
                //Verify with Google reCAPTCHA servers
                //Construct query paramters
                $query_content = http_build_query(array('secret'=>$secret,'response'=>$captcha));
                //Start curl
                $curl=curl_init();
                //Set options for cURL: url, return as value, do a post
                curl_setopt($curl, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS,$query_content);
                //Do the post to Google servers
                $response=curl_exec($curl);
                //Close cURL resource, free up system resources
                curl_close($curl);
                //Check curl response
                if ($response === false)
                    //set error in JSON format
                    $response='{"success": false, "error-codes": ["connection-failed"]}';
                //Use json_decode to decode 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 the form data
                        echo "<p>".$submission_error." Data check failed.</p>";
                    } else {
                        //Process data as required
                        if(isset($_POST['name']))
                            echo "<p>Welcome ".clean_data($_POST['message'])."</p>";
                        if(isset($_POST['message']))
                            echo "<p>Your message is: ".clean_data($_POST['name'])."</p>";
                    }
                }
            }
        ?>
     </body>
</html>

If the submission is normal, i.e. done by a human, 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. The data can be processed as required, for example, to send an email to a person handling enquires from a web page. This can include the web page url so that the page that generated the enquiry is known.

See Also

Author:  Published:  Updated:  

ShareSubmit to TwitterSubmit to FacebookSubmit to LinkedInSubmit to redditPrint Page

Do you have a question or comment about this article?

(Alternatively, use the email address at the bottom of the web page.)

 This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

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



Tek Eye Published Projects