CodeIgniter 4 AJAX Tutorial
About Lesson

What is Google reCaptcha?

Google reCAPTCHA is a free service offered by Google that helps protect websites from spam and abuse. It works by presenting challenges or puzzles to users to prove that they are human rather than automated bots. These challenges typically involve identifying objects in images, solving text-based puzzles, or simply checking a box to confirm that the user is not a robot.

There are several versions of reCAPTCHA available, each with varying levels of complexity and security features. The most common versions include:

  1. reCAPTCHA v2: This version presents users with a checkbox that they need to click to confirm they are human. In some cases, additional challenges like image recognition may be presented if the system suspects suspicious activity.

  2. reCAPTCHA v3: Unlike v2, this version does not require any user interaction or challenges. Instead, it runs in the background and assigns a score to each user based on their interactions with the website. Websites can then use this score to determine whether the user is likely to be a human or a bot.

  3. Invisible reCAPTCHA: This is similar to reCAPTCHA v2 but doesn’t require any interaction from the user. It automatically detects whether the user is a human or a bot based on their behavior on the website.

 

What are the benefits of using reCaptcha?

There are several benefits of Google reCaptcha which you can find below.

  • Spam Protection: One of the primary benefits of reCAPTCHA is its ability to protect websites from spam and abuse. By verifying that users are human and not bots, reCAPTCHA helps prevent automated attacks such as spam comments, form submissions, and account registrations.

  • Improved Security: reCAPTCHA helps enhance the security of websites by adding a layer of protection against automated scripts and bots. This reduces the risk of unauthorized access, data breaches, and other malicious activities.

  • Enhanced User Experience: While reCAPTCHA adds an extra step for users to prove they are human, it generally provides a smooth and seamless experience. Most users are familiar with the process and understand its importance in maintaining website security.

  • Data Protection: Google’s reCAPTCHA service is designed to prioritize user privacy and data protection. It complies with privacy regulations such as GDPR and ensures that user data is handled securely and responsibly.

 

Login with Mobile No. and OTP with reCAPTCHA

 

Get Google reCaptcha keys

You can skip this step if you already registered for Google reCAPTCHA v3 and have site and secret keys. To obtain Google reCAPTCHA keys for your website, follow these steps:

  1. Sign in to your Google account: Go to the Google reCAPTCHA website (https://www.google.com/recaptcha/admin/create) and sign in with your Google account. If you don’t have one, you’ll need to create one.

  2. Register your website: Once signed in, click on the “Admin Console” button at the top right corner of the page. This will take you to the reCAPTCHA Admin Console.

  3. Register your site: In the reCAPTCHA Admin Console, you’ll find an option to “Register a new site.” Click on it and fill out the form with the required information:

    • Label: Enter a label to identify your website.
    • reCAPTCHA type: Choose the type of reCAPTCHA you want to use (reCAPTCHA v2, Invisible reCAPTCHA, or reCAPTCHA v3).
    • Domains: Enter the domain(s) where you’ll be implementing reCAPTCHA. You can enter multiple domains if needed.
    • Owners: Add the email addresses of any additional users who should have access to manage reCAPTCHA settings for your site.
  4. Accept the terms of service: Make sure to review and accept the reCAPTCHA Terms of Service.

  5. Submit the form: After filling out the required information, click on the “Submit” button to register your site.

  6. Get your site key and secret key: Once your site is registered, you’ll be provided with two keys: a site key and a secret key. These keys are unique to your website and are used to integrate reCAPTCHA into your web pages.

Get Google reCaptcha keys

 

 

Step 1: Database Setup

CREATE TABLE `login_info` (
  `id` int(10) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `mobile_number` varchar(50) NOT NULL,
  `ip_address` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `status` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

ALTER TABLE `login_info`
  ADD PRIMARY KEY (`id`);

 

Step 2: Controller

Create a controller to handle CRUD operations. Create a new file named Login.php in the app/Controllers/loginfolder.

<?php
namespace App\Controllers\login;

use App\Controllers\BaseController;
use App\Models\user\UserModel;

class Login extends BaseController {

public function __construct() {
$db = db_connect();
$this->user = new UserModel($db);
}

public function index() {
$this->login();
}

public function login() {
$data = [];
$data ['content_title'] = "Login with Mobile Number and OTP";
$data ['main_content'] = "login/login";
echo view('innerpages/template', $data);
}

public function send_otp() {

// Google Recaptcha Keys
$site_key = '6Lc9XZQpAAAAACdCFVnAqwvXx08YTd3XhkEMC6yM';
$secret_key = '6Lc9XZQpAAAAAP_Opzt57_tTx5_mkn5yfl_iKJ-6';

$mobile_number = $this->request->getPost('mobile_number');
$captcha_response = trim($this->request->getPost('g-recaptcha-response'));
if($mobile_number) {
if($captcha_response != '') {
$check = array(
'secret' => $secret_key,
'response' => $this->request->getPost('g-recaptcha-response')
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($check));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);
if($response['success']) {
$where = [
"mobile_number" => $mobile_number,
];
$result = $this->user->getEntry($where);
$otp = $this->getOtp();
if($result) {
$data = [
'otp' => $otp,
'status' => '0',
];
$result = $this->user->updateEntry(['id' => $result->id], $data);
} else {
$data = [
"mobile_number" => $mobile_number,
'otp' => $otp,
'status' => '0',
];
$result = $this->user->addEntry($data);
}
if($result) {
$this->sendSMS("148397", $otp.'|', str_replace("+91", "", $mobile_number));
$json = [
'message' => 'OTP has been sent successfully',
'status' => true,
];
} else {
$json = [
'message' => 'Something went wrong. Please try again',
'status' => false,
];
}
} else {
$json = [
'message' => 'Invalid Captcha. Please try again.',
'status' => false,
];
}
} else {
$json = [
'message' => 'Invalid Captcha. Please try again.',
'status' => false,
];
}
} else {
$json = [
'message' => 'Enter your Mobile Number',
'status' => false,
];
}
echo json_encode($json);
}

public function verify_otp() {
$mobile_number = $this->request->getPost('mobile_number');
$otp = $this->request->getPost('otp');

$where = [
"mobile_number" => $mobile_number,
"otp" => $otp,
];
$result = $this->user->getEntry($where);
if($result) {
$data = [
'status' => '1',
];
$this->user->updateEntry(['id' => $result->id], $data);
$json = [
'message' => 'LoggedIn Successfully',
'location' => base_url('crud/list'),
'status' => true,
];
} else {
$json = [
'message' => 'Entered OTP is not a valid',
'status' => false,
];
}
echo json_encode($json);
}

function getOtp() {
$otp = rand(1, 9);
$otp .= rand(0, 9);
$otp .= rand(0, 9);
$otp .= rand(0, 9);
$otp .= rand(0, 9);
$otp .= rand(0, 9);
return $otp;
}

function sendSMS($message, $variables_values, $mobile_numbers) {
$url = 'https://www.fast2sms.com/dev/bulkV2';
$authorization = 'z015jdvEkGf2FRLYPu8ynTQ7MqecSDZAhUJgrm3Ai29MUhawp4XYzGbtS5Fr0uKWRVf';
$sender_id = 'CXSTCH';
$route = 'dlt';

$body = $url . '?authorization=' . $authorization . '&sender_id=' . $sender_id . '&message=' . $message . '&variables_values=' . urlencode($variables_values) . '&route=' . $route . '&numbers=' . $mobile_numbers;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);
if (curl_errno($ch)) {
// echo 'Error:' . curl_error($ch);
}
curl_close($ch);
}
}

 

Step 3: Model

Create a model to handle database operations. Create a new file named UserModel.php in the app/Models/userfolder.

<?php
namespace App\Models\user;

use CodeIgniter\Model;
use CodeIgniter\Database\ConnectionInterface;

class UserModel extends Model {

protected $db;

public function __construct(ConnectionInterface &$db) {
$this->db =& $db;
$this->table = 'login_info';
}

public function addEntry($data) {
$this->db->table($this->table)
->insert($data);

return $this->db->insertID();
}

public function getEntry($where) {
return $this->db->table($this->table)
->where($where)
->get()
->getRow();
}

public function getEntryList($where = 0) {
if($where) {
return $this->db->table($this->table)
->where($where)
->get()
->getResult();
} else {
return $this->db->table($this->table)
->get()
->getResult();
}

}

public function updateEntry($where, $data) {
return $this->db->table($this->table)
->where($where)
->set($data)
->update();
}

public function deleteEntry($where) {
return $this->db->table($this->table)
->where($where)
->delete();
}

}
 

 

Step 4: Create Views

Create views (login.php) in the app/Views/login folder for listing, creating, updating, and deleting records.

login.php

<!DOCTYPE html>
<html lang="en">

<head>
<title><?php echo $content_title; ?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>

</head>

<body>

<div class="container mt-5">
<div class="jumbotron">
<h2>Login with Mobile No. and OTP with reCAPTCHA</h2>
<p>CodeIgniter 4</p>
</div>
<div class="row">
<div class="col-sm-12 send-otp">
<form id="form-send-otp" method="post" autcomplete="off">
<div class="form-group">
<label>Mobile</label>
<input type="text" name="mobile_number" id="send_otp_mobile_number" class="form-control" placeholder="Enter mobile number" maxlength="10" required>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6Lc9XZQpAAAAACdCFVnAqwvXx08YTd3XhkEMC6yM"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Send OTP</button>
</div>
</form>
</div>

<div class="col-sm-12 verify-otp" style="display: none;">
<form id="form-verify-otp" method="post" autcomplete="off">
<div class="form-group">
<label>Mobile</label>
<input type="text" name="mobile_number" id="verify_otp_mobile_number" class="form-control" placeholder="Enter mobile number" maxlength="10" readonly>
</div>
<div class="form-group">
<label>OTP</label>
<input type="text" name="otp" class="form-control" placeholder="Enter OTP" maxlength="6" minlength="6" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Verify OTP</button>
</div>
</form>
</div>
</div>
</div>

<script>
$(document).ready(function() {

$("body").on("submit", "#form-send-otp", function(e) {
e.preventDefault();
let data = $(this).serialize();
$.post('<?php echo base_url("login/send-otp") ?>', data, function(result) {
alert(result.message);
if(result.status) {
$("#verify_otp_mobile_number").val($("#send_otp_mobile_number").val());
$(".send-otp").hide();
$(".verify-otp").show();
}
}, 'json');
});

$("body").on("submit", "#form-verify-otp", function(e) {
e.preventDefault();
let data = $(this).serialize();
$.post('<?php echo base_url("login/verify-otp") ?>', data, function(result) {
alert(result.message);
if(result.status) {
window.location.href = result.location;
}
}, 'json');
});

});
</script>

</body>

</html>

 

Step 5: Set Up Routes

Edit the app/config/Routes.php file to define routes for your controller.

$routes->get('login',               'login\Login::login');
$routes->post('login/send-otp', 'login\Login::send_otp');
$routes->post('login/verify-otp', 'login\Login::verify_otp');

 

Step 6: Run Project & Output

Login with Mobile No. and OTP with reCAPTCHA