etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

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.

How to add google recaptcha v2 in registration form using PHP

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 MySQL
PHP 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




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to add multiple custom markers on google map
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP MYSQL Advanced Search Feature
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple way to send SMTP mail using Node.js
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Programming Error Types
-----------------
Date Timestamp Formats in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.