PHP Contact Form with Google reCaptcha V3 Example Code

PHP Contact Form with Google reCaptcha V3 Example Code

Last Updated on July 27, 2023 by Subhash Jain

There are two main components/parts of Google reCaptcha Script Integration into your website form. Part I involves integration of the code into your website form page – we call it as Client Side Integration. Part II involves integration of the code into your website action page – we call it as Server Side Integration. If you want to know – How to Get Google reCaptcha Site and Secret key, please click the link.

Part I: Google reCaptcha Client Side Integration

Step 1: Paste this snippet with recaptcha Public key before the closing </head> tag on your HTML template:

<script src = 'https://www.google.com/recaptcha/api.js?render=reCaptcha_PUBLIC_KEY'> </script>
    //Paste this snippet in the JavaScript callback for an action on your website.
    <script>
    grecaptcha.ready(function(){
    grecaptcha.execute('reCaptcha_PUBLIC_KEY',
        {action: 'contact_us_action_form'}).then(function(token)
        {
            // Verify the token on the server.
            document.getElementById('captcha_token').value = token;
        });
    });
    </script>

Step 2: Insert this token in the “Hidden Field” of your form. Please note that on form load, this hidden field will populate the token value from above JS function automatically.

    <input type="hidden" id="captcha_token" name="captcha_token" />

Part II: Google reCaptcha Server Side Integration

Step 1: In the PHP action code, you need to paste at top this snippet. Please don’t forget to replace reCaptcha_PRIVATE_KEY with your registered private key.

if(isset($_POST['captcha_token'])) {
    // reCAPTCHA Settings
    $captcha = $_POST['captcha_token'];
    $ip = $_SERVER['REMOTE_ADDR'];
    $key = 'reCaptcha_PRIVATE_KEY';
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    //echo $full_url;

    // reCAPTCH response
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "$url");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "secret=$key&response=$captcha");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        //echo $output;
        // If you echo above $output, you will get JSON data as similar to shown below:-
        // Json:{ "success": true, "challenge_ts": "2020-11-22T10:53:46Z", "hostname": "www.mydomain.com",
        //   "score": 0.9, "action": "contact_us_action_form" }
    $data = json_decode($output);
    //print_r($data);
    // If request was NOT a valid reCAPTCHA token for your site, terminate script execution.
    if(isset($data->success) &&  $data->success === false) {
        die('reCaptcha Invalid');
        exit;
    }
    }
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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