PHP and Google reCAPTCHA Integration on Submitting a Form Tutorial
Introduction
In this tutorial, I will show you a way to Integrate PHP and Google reCAPTCHA for submitting a form. Here I will also teach you how to add reCAPTCHA to your site. The tutorial aims to provide students and new PHP Programmers to have a reference to learn with for securing their web applications. Here, images, snippets, and sample source codes are provided.
What is Google reCAPTCHA?
To prevent malicious malware from abusing your website, reCAPTCHA employs an advanced risk analysis engine and adaptive challenges. False users will be barred while real users can log in, make purchases, access pages, or create accounts.
How to Add reCaptcha to your site?
Go to https://www.google.com/recaptcha/admin/create. Fill in all the required fields to get your site key and secret key.
Then save the given Site Key and Secret Key.
Then, to add the Google reCaptcha. Here are the following scripts you need to add to you site. To display the reCaptcha checkbox.
Add the above script to your page header to include the Google Recaptcha API to your site. Then to add the check box, paste the following script to the location you want to display the Google reCaptcha Checkbox.
Verification
When submitting the form, make sure to verify the response using the google reCaptcha verification API. To verify the response, you will be needing the given secret key. Here's the following sample to do so.
- <?php
- $secret = "6Lck3IAiAAAAAJ7l_ghRD3hIjBT4wxEWQKP6LluJ";
- //Successfull Verification
- }else{
- //Verification Failed
- // user $response['error-codes'] to list all the error upon verification
- }
Example
The below snippet is an example PHP script that demonstrates the PHP and Google reCaptcha API. The source code result is a simple registration form app that registers the members of an organization. The form has a reCaptcha feature included both on the client and server sides.
index.php
- <?php
- session_start();
- include_once('register.php');
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
- <style>
- html, body{
- min-height:100%;
- width:100%;
- }
- .img-holder {
- text-align: center;
- height: 20vw;
- border: 1px solid;
- width: 100%;
- display: flex;
- justify-content: center;
- align-items: center;
- background: black;
- }
- .img-holder > img{
- max-height:calc(100%);
- max-width:calc(100%);
- object-fit:scale-down;
- object-position:center center;
- }
- </style>
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container-fluid px-5 my-3">
- <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
- <div class="card rounded-0 shadow">
- <div class="card-body">
- <div class="container-fluid">
- <?php if(isset($_SESSION['success_msg'])): ?>
- <div class="alert alert-success rounded-0">
- <?= $_SESSION['success_msg'] ?>
- </div>
- <?php unset($_SESSION); ?>
- <?php endif; ?>
- <?php if(isset($error_msg)): ?>
- <div class="alert alert-danger rounded-0">
- <?= $error_msg ?>
- </div>
- <?php unset($error_msg); ?>
- <?php endif; ?>
- <form action="" method="POST">
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="first_name" name="first_name" value="<?= (isset($_POST['first_name']) ? $_POST['first_name'] : "") ?>" required>
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="middle_name" name="middle_name" value="<?= (isset($_POST['middle_name']) ? $_POST['middle_name'] : "") ?>" required>
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="last_name" name="last_name" value="<?= (isset($_POST['last_name']) ? $_POST['last_name'] : "") ?>" required>
- </div>
- <div class="mb-3">
- <input type="email" class="form-control rounded-0" id="email" name="email" value="<?= (isset($_POST['email']) ? $_POST['email'] : "") ?>" required>
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="contact" name="contact" value="<?= (isset($_POST['contact']) ? $_POST['contact'] : "") ?>" required>
- </div>
- <div class="mb-3">
- </div>
- <?php if(isset($err_captcha)): ?>
- <div class="alert alert-danger rounded-0 mb-3">
- <?= $err_captcha ?>
- </div>
- <?php unset($err_captcha); ?>
- <?php endif; ?>
- <div class="mb-3 d-grid">
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
register.php
- <?php
- require_once("db-connect.php");
- if($_SERVER['REQUEST_METHOD'] == "POST"){
- $grr = $_POST['g-recaptcha-response'];
- $err_captcha = "Kindly check reCaptcha Checkbox before submitting the form.";
- }else{
- /**
- * Validate Google reCaptcha
- */
- // Secret key
- $secret = "your-secret-key";
- // Get verification response
- $sql = "INSERT INTO `members` (`first_name`, `middle_name`, `last_name`, `email`, `contact`)
- VALUES ('{$first_name}', '{$middle_name}', '{$last_name}', '{$email}', '{$contact}')";
- $insert = $conn->query($sql);
- if($insert){
- $_SESSION['success_msg'] = "Data has been saved successfully";
- exit;
- }else{
- $error_msg = "There's an error occurred while saving the data";
- }
- }else{
- $err_captcha = "reCaptcha Validation Failed. <br>";
- $err_captcha .= "<ul>";
- foreach($response['error-codes'] as $error){
- $err_captcha .= "<li>{$error}</li>";
- }
- $err_captcha .= "</ul>";
- }
- $err_captcha = "Please check the checkbox.";
- }
- }
- }
The complete source code of the above example application can be downloaded on this site for free. The download button is located below this article. The source code zip file also contains the sample or the dummy database schema.
DEMO VIDEO
That's the end of this tutorial. I hope this PHP and Google Recaptcha Integration Tutorial will help you with what you are looking for and will be useful for your current and future PHP Projects.
Explore more on this website for more Tutorials and Free Source Codes
Add new comment
- 656 views