How to integrate google recaptcha v3 in php?

Member

by kadin , in category: PHP General , 8 months ago

How to integrate google recaptcha v3 in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 8 months ago

@kadin 

To integrate Google reCAPTCHA v3 in PHP, follow these steps:

  1. Go to the Google reCAPTCHA website and register your site to get the reCAPTCHA keys (site key and secret key).
  2. Add the reCAPTCHA script to your HTML form where you want to add the reCAPTCHA verification.
1
<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITE_KEY"></script>


  1. Create a PHP script that will handle the form submission and reCAPTCHA verification.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $recaptcha_response = $_POST['g-recaptcha-response'];
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $data = array(
        'secret' => 'YOUR_SECRET_KEY',
        'response' => $recaptcha_response
    );

    $options = array(
        'http' => array (
            'header' => "Content-Type: application/x-www-form-urlencoded
",
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    $result = json_decode($result);

    if ($result->success) {
        // reCAPTCHA verification successful
        // Add code here to process the form submission
    } else {
        // reCAPTCHA verification failed
        echo 'reCAPTCHA verification failed';
    }
}
?>


  1. Replace 'YOUR_SITE_KEY' and 'YOUR_SECRET_KEY' with the reCAPTCHA keys you obtained in step 1.
  2. Add the 'g-recaptcha-response' field to your form.
1
2
3
4
5
<form action="your-php-script.php" method="post">
    <!-- your form fields here -->
    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
    <input type="submit" value="Submit">
</form>


  1. Run your PHP script and test the reCAPTCHA verification process.


That's it! You have successfully integrated Google reCAPTCHA v3 in PHP.