How to add Google reCAPTCHA v2 to the registration form using PHP
In the previous article, we explained how to add captcha in the PHP form, and in this article, you will learn how to add the Google reCAPTCHA v2 checkbox in your registration form using the PHP programming language.
The reCAPTCHA has some advantages over a normal captcha. It reduces the workload for the human as the distorted letters of captcha image sometimes cause difficulty for the human. The reCAPTCHA is more secure than captcha. It has a few lines of code and is easy to implement.
There are two versions of reCaptcha. The first displays some digits and words on the image to verify it, and the second shows to mark the checkbox "I'm not a robot". In this article, we are using the second one (reCAPTCHA v2). It validates the user to verify whether or not they are human.
Before integrating it, there are the key entities that we need for reCAPTCHA integration.
1. We need API keys. Search for 'Google reCaptcha API' on your browser, go to the valid link and click on it.
'Settings' -> 'reCAPTCHA Type' -> 'v2 Checkbox'Here, you will get 'SITE Key' and 'SECRET Key'.
2. We need to add the Google recaptcha api javascript library in the script.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
3. Place the following code where you want to add the reCAPTCHA box in the form and replace the 'ENTER_SITE_KEY' with your generated site key.
<div class="g-recaptcha" data-sitekey="ENTER_SITE_KEY"></div>
4. At last, we need to verify the checked reCAPTCHA box using the following string. Make sure to replace the '$secret_key' with your generated secret key. It returns data in the JSON format.
file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);
Complete Code- How to add Google reCAPTCHA v2 in registration form using PHP
Here, we have created a main file 'index.php' that you want to call in the browser. It contains the registration form fields with reCAPTCHA checkbox at the end. When the user submit this form, it will redirect to 'verify_recaptcha.php' page.
Make sure to replace 'ENTER_SITE_KEY' with your generated SITE key.
index.php
<html>
<head>
<title>Google reCAPTCHA v2 Checkbox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class="container">
<form action="verify_recaptcha.php" method="post">
<div class="form-group">
<input type="text" name="empname" value="" placeholder="Employee Name" required="" />
</div>
<div class="form-group">
<input type="email" name="email" value="" placeholder="Email" required="" />
</div>
<div class="form-group">
<input type="text" name="phone" value="" placeholder="Phone" required="" />
</div>
<div class="form-group">
<textarea name="text" name="address" placeholder="Address.." required="" ></textarea>
</div>
<div class="g-recaptcha" data-sitekey="ENTER_SITE_KEY"></div>
<input class="btn btn-info" type="submit" name="submit" value="SUBMIT" >
</form>
</div>
</body>
</html>
verify_recaptcha.php
Here, we have validated all the entered field data and validated the google reCAPTCHA checkbox.
<?php
$returnMsg = '';
if(isset($_POST['submit'])){
// Form fields validation check
if(!empty($_POST['empname']) && !empty($_POST['email']) && !empty($_POST['phone'])){
// reCAPTCHA checkbox validation
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
// Google reCAPTCHA API secret key
$secret_key = 'ENTER_YOUR_SECRET_KEY';
// reCAPTCHA response verification
$verify_captcha = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);
// Decode reCAPTCHA response
$verify_response = json_decode($verify_captcha);
// Check if reCAPTCHA response returns success
if($verify_response->success){
$name = $_POST['empname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
// Send user registration notification to the admin
$to = "This email address is being protected from spambots. You need JavaScript enabled to view it. ";
$subject = "New User Registration";
$body = "<h1>New User Details</h1>
<p><strong>User Name: </strong>".$name."</p>
<p><strong>Email: </strong>".$email."</p>
<p><strong>Phone: </strong>".$phone."</p>
<p><strong>Address:<strong>".$address."</p>
";
// Set email header content type
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
// Send email to Admin
@mail($to,$subject,$body,$headers);
$returnMsg = 'Your registration has been submitted successfully.';
}else{
$returnMsg = 'reCaptch verification failed, please verify again.';
}
}else{
$returnMsg = 'Please check the CAPTCHA box.';
}
}else{
$returnMsg = 'Please fill all the required fields.';
}
}
echo $returnMsg;
?>
If the form fields validation and reCAPTCHA verification have succeeded, it returns 'Your registration has been submitted successfully' to the browser.
Related Articles
PHP sanitize input for MySQLPHP random quote generator
PHP String Contains
PHP calculate percentage of total
PHP Fix: invalid argument supplied for foreach
Locking files with flock()
How to Pass an Array as URL Parameter in PHP
Google maps custom marker
How to use google map street view api on webpage
Get current visitor's location using HTML5 Geolocation API and PHP
PHP code to generate Captcha and add in contact form with Validation
How to store Emoji character in MySQL using PHP
PHP7 Password Hashing
Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
Sending form data to an email using PHP