I am trying to upgrade from ReCaptcha v1 (in use and working good since 2017) to ReCaptcha v3 as ReCaptcha is not compatible with any of the PHP v8's. I started setting it up (got site and secret keys) and coding for 2 versions of ReCaptcha v3 (1. Automatically bind the challenge and 2. Programmitically invoke the challenge). I like 2. better. Anyway, the coding format for these 2 ReCaptcha v3's are different than what is currently in use on the HTML front side of my on-line submission pages. The coding for 1. & 2. are below. The Curly braces and tab stops (4+ spaces) were removed from the coding to avoid getting the following message: 'Curly braces and tab stops (4+ spaces) may only be used when posting code.'. Each of the 2 versions below has 3 parts. Only part 1 of both (Load the JavaScript API) is the same coding format as the original.

I have a few questions:

  1. Where in the program file would the coding listed under both part 2's go ? (e.g. Add a callback function to handle the token & Call grecaptcha.execute on each action you wish to protect.) As they are <script> functions it looks like they may go in the <head> section with the other <script> stuff.

  2. Where in the program file would the coding listed under both 1. part 3 go ? (e.g. Add attributes to your html button) In the original, in the <body> section in the part where the ReCaptcha appears on the screen is the following: <div align="center" class="g-recaptcha" data-sitekey="(site key code)"></div>

  3. Under 2. part 3: Send the token immediately to your backend with the request to verify (/recaptcha/docs/verify), how is this done ? (I haven't looked at the PHP code in the backend side file yet. Want to get the front end HTML stuff set first then I'll see about configuring ReCaptcha v3 in the PHP file)

ReCaptcha v3 Coding:

  1. Automatically bind the challenge to a button

The easiest method for using reCAPTCHA v3 on your page is to include the necessary JavaScript resource and add a few attributes to your html button.

Part 1 - Load the JavaScript API.

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

Part 2 - Add a callback function to handle the token.

<script>
function onSubmit(token)document.getElementById("demo-form").submit();
</script>

Part 3 - Add attributes to your html button.

<button class="g-recaptcha" 
        data-sitekey="reCAPTCHA_site_key" 
        data-callback='onSubmit' 
        data-action='submit'>Submit</button>
  1. Programmatically invoke the challenge

If you wish to have more control over when reCAPTCHA runs, you can use the execute method in grecaptcha object. To do this, you need to add a render parameter to the reCAPTCHA script load.

Part 1 - Load the JavaScript API with your sitekey.

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

Part 2 - Call grecaptcha.execute on each action you wish to protect.

<script>
function onClick(e)
e.preventDefault();
grecaptcha.ready(function()
grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token)
// Add your logic to submit to your backend server here.););
</script>

Part 3 - Send the token immediately to your backend with the request to verify.

  1. It seems that you have registered and received your keys, step 1 completed.

  2. In your HTML file, add the ReCaptcha JavaScript library to the <head> section -

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

  3. Create an HTML form with the necessary input fields and a ReCaptcha <div> element. This can be placed anywhere inside the <body> section -

    <form method="post" action="validate.php">
    <!-- Add your form fields here -->

    <div class="g-recaptcha" data-sitekey="RECAPTCHA_SITE_KEY"></div>

    <button type="submit" name="submit">Submit</button>
    </form>

4.Validate the ReCaptcha Response (validateCaptcha.php) -
-Create a PHP file (validateCaptcha.php or any other name you require) to handle the form submission and validate the ReCaptcha response.
-Retrieve the ReCaptcha response token from the '$_POST array'.
-Send a POST request to the ReCaptcha API endpoint for verification using your Secret key.
-Process the API response and perform the desired actions based on the ReCaptcha result -

<?php
$recaptcha_secret_key = 'RECAPTCHA_SECRET_KEY';
$recaptcha_response = $_POST['g-recaptcha-response'];

$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_data = array(
    'secret' => $recaptcha_secret_key,
    'response' => $recaptcha_response
);

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

$recaptcha_context = stream_context_create($recaptcha_options);
$recaptcha_result = file_get_contents($recaptcha_url, false, $recaptcha_context);
$recaptcha_json = json_decode($recaptcha_result);

if ($recaptcha_json->success) {
    // ReCaptcha validation successful, process the form submission
    // Your form processing code goes here
} else {
    // ReCaptcha validation failed, display an error message or take appropriate action
    // Example: redirect back to the form page with an error message
    header('Location: form.php?error=recaptcha');
    exit();
}
?>

This should handle the basic authentication/validation.

Andre Ret - I followed your instructions. Got an error on the front end (HTML side not PHP): ERROR for site owner: Invalid key type.

Here is the applicable code (less Curly braces and tab stops (4+ spaces) as message will not send otherwise:

<head>
<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
<script>
function onClick(e)
e.preventDefault();
grecaptcha.ready(function()
grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token)
// Add your logic to submit to your backend server here.
);
);
</script>
</head>
<body>
<div class="content">
<form action="LucidTruth_email_form.php" method="post" enctype="multipart/form-data" name="ContactLucidTruth" id="ContactLucidTruth">
<table width="540" border="1" align="center"><tr>
<td>
<p align="center" ><span class="regular">* = required info.</span></p>
<p align="center"><span id="name">
<label for="Name" style="font-weight: bold"><span class="regular">* Name : </span></label>
<input type="text" name="Name" id="Name" />
</span></p>
<p align="center"><span id="email">
<label for="Email" style="font-weight: bold"><span class="regular">* E-Mail Address :</span></label>
<input type="text" name="Email" id="Email" />
</span></p>
<p align="center"><span id="phonenumber">
<label for="Phone" style="font-weight: bold"><span class="regular"> Phone Number : </span></label>
<input type="text" name="Phone" id="Phone" />
</span></p>
<p align="center" class="maintext"> <span id="comments">
<label for="Message"><span class="regular" style="font-weight: bold">* Comments</span></label>
<br />
<textarea name="Message" id="Message" cols="45" rows="5"></textarea>
</span></p>
<div align="center"class="g-recaptcha"data-sitekey="6LcEpx4mAAAAAIifggIv8xVUUUyYtymrKl4f9zYa"></div>
<p align="center">
<button type="submit" name="submit"><input type="submit" name="Submit" id="Submit" value="Submit" /></button>
<input type="reset" name="Cancel" id="Cancel" value="Cancel" />
</p>
</table></form>
  <!-- end .content --></div>
</body>
commented: Invalid Key Type refers to one of your 2 keys that is the wrong type. Make sure your keys is for v3 and not v1 or v2. +15

I got new site and secret keys making sure they were for ReCaptcha v3. They were. Put new site key in front end file. Still got Invalid Key Type error. Attached is relevant code in a code block. Below (not in code block, curly braces, etc. removed) is the following script (its also in the code block, 2nd script in head). This coding I got from the ReCaptcha 3 website where site keys, etc. are obtained. I singled this section out because it contains the following comment: '// Add your logic to submit to your backend server here.'. There is no 'logic' here as I don't know what it would be. Could this be the reason why the Invalid Key Type error is happening ?
<script>
function onClick(e)
e.preventDefault();
grecaptcha.ready(function()
grecaptcha.execute('reCAPTCHA_site_key', action: 'submit').then(function(token)
// Add your logic to submit to your backend server here.);
);
</script>
Code Block:

<head>
<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
    <script>
          function onClick(e) {
            e.preventDefault();
            grecaptcha.ready(function() {
              grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {
                  // Add your logic to submit to your backend server here.
              });
            });
          }
      </script>
    </head>

    <body>

    <div class="container">
    <form action="LucidTruth_email_form.php" method="post" enctype="multipart/form-data" name="ContactLucidTruth" id="ContactLucidTruth">
        <table width="540" border="1" align="center">
          <tr>
            <td>
        <p align="center" ><span class="regular">* = required info.</span></p>
            <p align="center"><span id="name">
              <label for="Name" style="font-weight: bold"><span class="regular">* Name : </span></label>
              <input type="text" name="Name" id="Name" />
            </span></p>
            <p align="center"><span id="email">
            <label for="Email" style="font-weight: bold"><span class="regular">* E-Mail Address :</span></label>
            <input type="text" name="Email" id="Email" />
            </span></p>
          <p align="center"><span id="phonenumber">
              <label for="Phone" style="font-weight: bold"><span class="regular"> Phone Number : </span></label>
              <input type="text" name="Phone" id="Phone" />
            </span></p>
            <p align="center" class="maintext"> <span id="comments">
              <label for="Message"><span class="regular" style="font-weight: bold">* Comments</span></label>

              <br />
    <textarea name="Message" id="Message" cols="45" rows="5"></textarea>
            </span></p>
       <div align="center"  class="g-recaptcha" data-sitekey="6LcJ11MmAAAAAB3qtUhQCE7T1YIHx3JJgI2VtK2B"></div>     

        <p align="center">
              <button type="submit" name="Submit" id="Submit" value="Submit" />Submit</button>
              <button type="reset" name="Cancel" id="Cancel" value="Cancel" />Cancel</button>
        </p>


    </table> 
        </form>
      <!-- end .content --></div>
    </body>
commented: '// Add your logic to submit to your backend server here' refres to the code that you want to execute once Captcha validated. On which line and what c +15

Did some further work on debugging this. Used the original ReCaptcha data site key (from 2017) and tested webpage. No more Invalid Key Type error. All new ReCaptcha 3 coding in place unchanged. When I filled out and submitted form, got a different error. Site changes to a URL page not found anywhere in the coding: https://www.rebhellionrecords.com/form.php?error=recaptcha (the correct page it was supposed to switch to is: https://www.rebhellionrecords.com/LucidTruth_email_form.php). Anyway, I then changed the ReCaptcha secret key back to the original one from 2017 on the /LucidTruth_email_form.php file. The next test submission worked. Now the original final question can be tested: Will the submission form still work when switched from PHP v7.4 to one of the new PHP v8.x's ? The original problem was Recaptcha not being compatible with any PHP v8.x's (I think there's v8.1 - 8.4) but ReCaptcha 3 is supposed to be compatible with a PHP v8.x. I'll be testing that and putting test results here.

commented: I am using v8.2 php and my Captcha works fine. Let us know how your testing goes. +15

PHP 8.2 is the latest version not 8.4. Other 8.x versions are 8.0 & 8.1. Anyway, all the original (from 2017) ReCaptcha key codes worked. Only the new ReCaptcha 3 key codes gave the invalid code error. And finally, the tests were successful and form submission worked properly. ReCaptcha 3 is compatible with PHP 8.2. Next step for me is to do the same as done on this "guinea pig" to all my other submission pages on a total of 6 domains... Thanks for your help, Dani & AndreRet.

commented: Only a pleasure! +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.