javascript - How to run recaptcha 2 in html and php?

one text

Solution:

If you can't change action="recaptcha.php", you need to use AJAX to verify the responses.

So, Your index.html should be like

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post"  action="/cms/common/sendEmail" enctype="multipart/form-data"  class="valida tc"  id="thisForm">
    <input type="hidden" name="lang" value="tch" />
    <tr>
    <td>
    <div id="recaptcha" ></div>
    </td>
    </tr>
<tr>
<td class="submitBtnWrap"><input type="submit" value="送出" class="roundBtn" /><span class="at-error"></span></td>
</tr>
</table>
</form>

<!-- Add jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Add recaptcha explicitly -->
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>

<!-- render and verify by ajax -->
<script>

    var onloadCallback = function() {
        grecaptcha.render('recaptcha', {
            'sitekey' : '6Lc9oGIaAAAAAMK6Q4ZZ_qYzlvVCV1nydMLDUUoZ',
            'callback' : verifyCallback,
        });
    }

    var verifyCallback = function(response) {
        $.post('recaptcha.php', {'g-recaptcha-response' : response}, function(data){
            alert(data);
        });
    };
        
</script>
</body>
</html>

your recaptcha.php:

<?php
    $public_key = "6Lc9oGIaAAAAAMK6Q4ZZ_qYzlvVCV1nydMLDUUoZ";
    $private_key = "6Lc9oGIaAAAAAEthTaDOcm3VJ9Uldizbl6ZDKQ2_";
    $url = "https://www.google.com/recaptcha/api/siteverify";
        
    if(isset($_POST['g-recaptcha-response'])){

        $response_key = $_POST['g-recaptcha-response'];
        $response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
        $response = json_decode($response);

        if($response->success == 1)
        {
            echo "Your information was valid...";
        }else{
            echo "You are a robot and we don't like robts.";
        }
    }
?>

Source