How to Add Captcha in PHP Registration Form

How to Add Captcha in PHP Registration Form

To add the Google CAPTCHA in PHP HTML Form. In this post, we will show you how to integrate or add google captcha in PHP HTML forms(registration, login, contact form).

And using the captcha with PHP html forms, you can easily validate your contact, registration, login and other form data in PHP.

How to Add Google Captcha in PHP Registration Form

Use the below given easy steps to add captach in PHP html forms(registration, login, contact etc.):

  1. Create Table In DB by Sql Query
  2. Create Database Connection PHP File
  3. Register your website on Google Re captcha and Get All Details
  4. Create User Registration Form with Captcha Validation In PHP
  5. Create PHP File to Check Captcha and Save User Details

Step 1: Create Table In DB by Sql Query

First of all, open your phpmyadmin and run the following sql query. To create table into your selected database:

CREATE TABLE `users1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(250) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 2: Create a Database Connection PHP File

In this step, create a file name db.php and add the following code into db.php file:

<?php
	$servername='localhost';
	$username='root';
	$password='';
	$dbname = "my_db";
	$conn=mysqli_connect($servername,$username,$password,"$dbname");
	  if(!$conn){
		  die('Could not Connect MySql Server:' .mysql_error());
		}
?>

Step 3: Register your website on Google Re captcha and Get All Details

To add google recaptcha to your website you need to register your website here https://www.google.com/recaptcha/admin. Then get your site key and secret key.about:blank

Step 4: Create User Registration Form with Captcha Validation In PHP

In this step, create user registration form that named registration.php and add google captcha validation.

So, open registration.php and add the following code into it:

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
      <title>How to Add Captcha in PHP Registration Form</title>
       <!-- CSS -->
       <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

       <script src="https://www.google.com/recaptcha/api.js" async defer></script>
   </head>
   <body>
      <div class="container mt-5">
          <div class="card">
            <div class="card-header text-center">
              Add Google Captcha in PHP Registration Form
            </div>
            <div class="card-body">
              <form action="validate-captcha.php" method="post">

                <div class="form-group">
                  <label for="exampleInputEmail1">Name</label>
                  <input type="text" name="name" class="form-control" id="name" required="">
                </div>                                

                <div class="form-group">
                  <label for="exampleInputEmail1">Email address</label>
                  <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" required="">
                  <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
                </div>

                <div class="form-group">
                  <label for="exampleInputEmail1">Password</label>
                  <input type="password" name="password" class="form-control" id="password" required="">
                </div>                   

                <div class="form-group">
                  <label for="exampleInputEmail1">Confirm Password</label>
                  <input type="password" name="cpassword" class="form-control" id="cpassword" required="">
                </div>   

                <div class="g-recaptcha" data-sitekey="Your Site Key"></div>

                <input type="submit" name="password-reset-token" class="btn btn-primary">
              </form>
            </div>
          </div>
      </div>

   </body>
</html>

Step 5: Create PHP File to Check Captcha and Save User Details

Now, create validate-captcha.php file and add the following code into your validate-captcha.php file.

<?php
if(isset($_POST['submit']) && $_POST['g-recaptcha-response']!="")
{

 include "db.php";

 $secret = 'You Site Key';

 $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);

 $responseData = json_decode($verifyResponse);

 if($responseData->success)
 {

  $name = $_POST['name'];
  $email = $_POST['email'];
  $pass = $_POST['password'];
  
  mysqli_query($conn, "INSERT INTO users(name, email ,password) VALUES('" . $_POST['name'] . "', '" . $_POST['email'] . "', '" . md5($_POST['password']) . "')");

  echo "User registration form with captcha validation has been successfully saved";

 }
}

The validate-captcha.php file code will validate your captach and then store user registration data into database table.

Important Note

Don’t forget to add site-key on registration.php form

Don’t forget to add site-secret on validate-captcha.php file.

Conclusion

Thats all, this is how to create user registration form with google reCAPTCHA using PHP and MySQL.

Note that, You can customize this code further as per your requirement.

If you any question and suggestion. Please feel free to give comments on this tutorial.

Recommended PHP Posts:

  1. Autocomplete Search Box in PHP MySQL
  2. Compare Arrays PHP | PHP array_diff() Function
  3. Get, Write, Read, Load, JSON File from Url PHP
  4. Functions: Remove First Character From String PHP
  5. Remove Specific/Special Characters From String In PHP
  6. How to Replace First and Last Character From String PHP
  7. Reverse String in PHP
  8. Array Push, POP PHP | PHP Array Tutorial
  9. PHP Search Multidimensional Array By key, value and return key
  10. json_encode()- Convert Array To JSON | Object To JSON PHP
  11. PHP remove duplicates from multidimensional array
  12. PHP Remove Duplicate Elements or Values from Array PHP
  13. Get Highest Value in Multidimensional Array PHP
  14. PHP Get Min or Minimum Value in Array

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *