Sunday, 10 September 2023

Google reCAPTCHA

Step one: sign up recaptcha in Google.

It is free. Get GOOGLE_RECHAPTCHA_SECRET and GOOGLE_RECHAPTCHA_SITE_KEY

Need to add domain with this recaptcha. Do not need to add sub domain. Can add multiple domains

Step two: client side

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="{$siteKey}"></div>

//after check, may want to hide error. Put codeback code here
var recaptchaCallback = function() {

}

Step three: server side validation

User response can be found in $_POST['g-recaptcha-response']

public static function verifyRecaptcha($userResponse)
{
    $url = "https://www.google.com/recaptcha/api/siteverify";
    $curl = curl_init($url);

    $post = ['secret' => getenv('GOOGLE_RECHAPTCHA_SECRET'), 'response' => $userResponse];
    $post = http_build_query($post);

    curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");

    $response = curl_exec($curl);
    curl_close($curl);

    //see what we get
    $result = json_decode($response, true);

    return $result['success'] ?? false;
}

React component for Google reCAPTCHA v2

npm install --save react-google-recaptcha

No comments:

Post a Comment