Categories :

reCAPTCHA V3 Example in PHP

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
## reCAPTCHA V3 key define ##
#client-side
define(‘RECAPTCHA_SITE_KEY’, ‘reCAPTCHA_site_key’); // define here reCAPTCHA_site_key
#server-side
define(‘RECAPTCHA_SECRET_KEY’, ‘reCAPTCHA_secret_key’); // define here reCAPTCHA_secret_key

class Captcha {
public function getCaptcha($SecretKey) {
$data = array(
‘secret’ => RECAPTCHA_SECRET_KEY,
‘response’ => $SecretKey
);
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, “https://www.google.com/recaptcha/api/siteverify”);
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response_data = curl_exec($verify);
$response_data = json_decode($response_data);
curl_close($verify);
//echo “<pre>”; print_r($response_data); echo “</pre>”;
return $response_data;
}
}

///////////////////////////// OR /////////////////////////////
/*
class Captcha {
public function getCaptcha($SecretKey) {
$Resposta = file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret=” . RECAPTCHA_SECRET_KEY . “&response={$SecretKey}”);
$Retorno = json_decode($Resposta);
return $Retorno;
}
}
*/

if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
//echo “<pre>”; print_r($_REQUEST); echo “</pre>”;
$ObjCaptcha = new Captcha();
$Retorno = $ObjCaptcha->getCaptcha($_POST[‘g-recaptcha-response’]);
//echo “<pre>”; print_r($Retorno); echo “</pre>”;
if ($Retorno->success) {
echo ‘<p style=”color: #0a860a;”>CAPTCHA was completed successfully!</p>’;
} else {
$error_codes = ‘error-codes’;
if (isset($Retorno->$error_codes) && in_array(“timeout-or-duplicate”, $Retorno->$error_codes)) {
$captcha_msg = “The verification expired due to timeout, please try again.”;
} else {
$captcha_msg = “Check to make sure your keys match the registered domain and are in the correct locations.<br> You may also want to doublecheck your code for typos or syntax errors.”;
}
echo ‘<p style=”color: #f80808;”>reCAPTCHA error: ‘ . $captcha_msg . ‘</p>’;
}
}
?>

<div class=”contact_form”>
<div class=”” style=”margin-top:0px;margin-bottom:15px;”>
<div class=”” style=”width:50%”>
<form id=”Form1″ name=”Form1″ action=”” method=”POST”>
<label for=”fname”>First Name*</label><br>
<input type=”text” name=”fname” id=”fname” required autofocus><br><br>

<label for=”lname”>Last Name*</label><br>
<input type=”text” name=”lname” id=”lname” required><br><br>

<input type=”hidden” id=”g-recaptcha-response” name=”g-recaptcha-response”><br>
<input type=”submit”>
</form>
</div>
</div>
</div>

<script src=”https://www.google.com/recaptcha/api.js?render=<?php echo RECAPTCHA_SITE_KEY; ?>”></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute(‘<?php echo RECAPTCHA_SITE_KEY; ?>’, {action: ‘homepage’}).then(function (token) {
document.getElementById(‘g-recaptcha-response’).value = token;
});
});
</script>
</body>
</html>

22 Replies to “reCAPTCHA V3 Example in PHP”

  1. Also If you want to use cURL You should use belove class script:

    class Captcha{
    public function getCaptcha($SecretKey){
    $data = array(
    'secret' => RECAPTCHA_SECRET_KEY,
    'response' => $SecretKey
    );
    $verify = curl_init();
    curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify&quot;);
    curl_setopt($verify, CURLOPT_POST, true);
    curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
    $response_data = curl_exec($verify);
    $response_data = json_decode($response_data);
    curl_close($verify);
    /*var_dump($response_data);*/
    return $response_data;
    }
    }

  2. Replace this javascript:

    function grecaptcha_execute(){
    grecaptcha.execute('', {action: 'homepage'}).then(function(token) {
    document.getElementById('g-recaptcha-response').value=token;
    });
    }
    grecaptcha.ready(function() {
    grecaptcha_execute();
    });
    // On submit get any error recall grecaptcha_execute(); function

  3. Unfortunately still having the same error after changing the javascript to the one above. It seems like response = $SecretKey does nothing. Where is $SecretKey value extracted from?

  4. In three days of banging my head up against recaptcha v3, this is the ONLY example I have found that is complete, make sense, AND works! Thank you!

  5. How do i get the latest values of fname and lname in PHP? It would be nice if I get them in the part which says "CAPTCHA was completed successfully!" so I can mail those or put in the database.

  6. Hello Mich.

    Please use and try this code for insert latest fname and lname in databse.

    ## reCAPTCHA V3 key define ##
    #client-side
    define('RECAPTCHA_SITE_KEY', 'reCAPTCHA_site_key'); // define here reCAPTCHA_site_key
    #server-side
    define('RECAPTCHA_SECRET_KEY', 'reCAPTCHA_secret_key'); // define here reCAPTCHA_secret_key

    class Captcha {
    public function getCaptcha($SecretKey) {
    $data = array(
    'secret' => RECAPTCHA_SECRET_KEY,
    'response' => $SecretKey
    );
    $verify = curl_init();
    curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify&quot;);
    curl_setopt($verify, CURLOPT_POST, true);
    curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
    $response_data = curl_exec($verify);
    $response_data = json_decode($response_data);
    curl_close($verify);
    return $response_data;
    }
    }

    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $ObjCaptcha = new Captcha();
    $Retorno = $ObjCaptcha->getCaptcha($_POST['g-recaptcha-response']);
    if ($Retorno->success) {
    // echo 'CAPTCHA was completed successfully!';

    ###### PUT IN THE DATABASE ######
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $sql = "INSERT INTO $dbname (firstname, lastname) VALUES ($fname,$lname)";

    if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
    } else {
    echo "Error: " . $sql . "
    " . $conn->error;
    }

    } else {
    $error_codes = 'error-codes';
    if (isset($Retorno->$error_codes) && in_array("timeout-or-duplicate", $Retorno->$error_codes)) {
    $captcha_msg = "The verification expired due to timeout, please try again.";
    } else {
    $captcha_msg = "Check to make sure your keys match the registered domain and are in the correct locations.
    You may also want to doublecheck your code for typos or syntax errors.";
    }
    echo 'reCAPTCHA error: ' . $captcha_msg;
    }
    }

    I you have any query then contact me.

  7. I want the code and it works. But can you write it the same ,instead use the curl ,because I think the curl would work much better. Thank you

Leave a Reply

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