How to add Recaptcha 3 on my PHP website
- Article
- Comment
Just follow the steps to get it implemented on you website.
- Go to the reCAPTCHA website (https://www.google.com/recaptcha/intro/v3.html) and click on the “Admin Console” button.
- Sign in with your Google account or create a new one if you don’t have one already.
- Register your website by providing a name and the domain name of your website.
- After registering your website, you will be given a Site Key and a Secret Key. You will need these keys to integrate reCAPTCHA v3 with your website.
- Add the reCAPTCHA script to your website’s HTML code. This should be placed in the <head> section of your HTML code.
<script src="https://www.google.com/recaptcha/api.js?render=site_key"></script>
Replace “site_key” with your Site Key.
- Add the reCAPTCHA verification code to your website’s JavaScript code. This should be called when the user submits a form.
grecaptcha.ready(function() {
grecaptcha.execute('site_key', {action: 'submit'}).then(function(token) { // Add code to submit the form with the token });
});
Replace “site_key” with your Site Key.
- Verify the reCAPTCHA response on your server-side code. This should be done to ensure that the user is not a robot. The response parameter contains the token generated by reCAPTCHA.
$response = $_POST['g-recaptcha-response'];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array( 'secret' => 'secret_key', 'response' => $response );
$options = array( 'http' => array ( 'method' => 'POST', 'content' => http_build_query($data) ) );
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response_data = json_decode($result);
if ($response_data->success) { // The user is not a robot, continue with your form processing logic
} else { // The user is a robot, display an error message
}
Replace “secret_key” with your Secret Key.
That’s it! You have done the reCAPTCHA v3 integration with your PHP website.