Google reCaptcha v3 PHP Form using CURL

, ,

This goes in the form page within the header with the public site key where the X's are.

<script src=""></script>

  grecaptcha.ready(function() {
      document.getElementById('contactform').addEventListener("submit", function(event) {
        grecaptcha.execute('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', {action: 'contactform'}).then(function(token) {
           document.getElementById("recaptchaResponse").value= token; 
      }, false);

This is the form

<form action="send.php" method=post id=contactform>
Name: <input type="text" name="name" value=""><br />
Email: <input type="text" name="email" value=""><br />

<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
<input type=submit value=" Send ">

Then within the send.php file is where we are doing the checking of the captcha submission. The secret key gets placed where the X's are.


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {

    $recaptcha_response = $_POST['recaptcha_response'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => RECAPTCHA_V3_SECRET_KEY, 'response' => $recaptcha_response)));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $arrResponse = json_decode($response, true);
    // verify the response
    if($arrResponse["success"] == '1' && $arrResponse["score"] >= 0.5) {
        // valid submission
        // go ahead and do necessary stuff
    } else {
        // spam submission
        // show error message



Posted on

May 19, 2021

Submit a Comment

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