ReCaptcha V3 Implementation

PHP Code Snippets ReCaptcha V3 Implementation
Share:

About

In this post, we’ll learn how to implement reCAPTCHA on a website.

Recaptcha is used to confirm that the user interaction on your site was made by a human and not by some script. For example, if you have a contact form on your website you would want to implement some human verification to prevent getting spammed by bots.

In the code below we’ll see how to add the necessary code to the frontend and how to implement it with PHP in the backend.

Recaptcha SignUp

First you need to create a recaptcha: https://www.google.com/recaptcha/admin/create   

Then you will get a public and private key that you will need leter.(private for backend, public for frontend)

Note: Make sure you keep your private key secure. The recaptcha created with the keys in this tutorial was already deleted before this post went online so there is no security risk here.

Code:

html
Replace the key in grcaptcha.execute(“”) and in the script src https://www.google.com/recaptcha/api.js?render= with your public key.
<!DOCTYPE html>
<html>
    <head>
        <title>Send Email</title>
    </head>
    <script src="https://www.google.com/recaptcha/api.js?render=6LccbssbAAAAALAy5UWhJSo2xPBz1wuKCUroCVcX"></script>
    <script>
        grecaptcha.ready(function() {
            grecaptcha.execute("6LccbssbAAAAALAy5UWhJSo2xPBz1wuKCUroCVcX", {action: "homepage"}).then(function(token) {
               document.getElementById("token").value = token;
            });
        });
    </script>
    <body>
        <h3>Send Email</h3>
        <form method="post" action="/Code%20Examples/php/recaptcha/sendEmail.php">
            <input type="text" name="email">
            <input type="submit" value="Send">
            <input type="hidden" id="token" name="token">
        </form>
    </body>
</html>
PHP
In the data array replace the key for ‘secret’ with your private key.
<?php

//Entry point///////////////////////////////////////////////////////

$recaptcha = $_POST["token"];

if(checkCaptcha($recaptcha))
    sendEmail($_POST["email"]);
else
    die("Recaptcha failed!");

///////////////////////////////////////////////////////////////////

//Functions////////////////////////////////////////////////////////

function checkCaptcha($recaptcha){
    $url = 'https://www.google.com/recaptcha/api/siteverify';

    $data = array(
        'secret' => '6LccbssbAAAAACImPfvTUtXTwtlbt-4XErLxyiow',
        'response' => $recaptcha
    );

    $options = array(
        'http' => array (
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );

    $context  = stream_context_create($options);
    $verify = file_get_contents($url, false, $context);
    $captcha_success = json_decode($verify);
 
    return $captcha_success->success;
}

function sendEmail($email){
    echo "Email was sent.";
    //Not really... we would have to implement the code but you get the idea of this demo.
    //If you would like to know how to send an emails with PHP check out this post I made:
    //https://eecs.blog/php-sending-emails/
    //Also check out this post on sanitizing your input data.
    //https://eecs.blog/php-string-sanitization/
}

///////////////////////////////////////////////////////////////////

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger