Codeigniter 4 Google ReCaptcha V2 Example Tutorial
In this article, we will explain to you how to create the Codeigniter 4 Google Recaptcha v2 Form Validation Example. normally captcha is used for security purposes and only human users can pass through. computers or bots are not solving a captcha.
Now we will learn about captcha that how to integrate the Google reCAPTCHA v2 in Codeigniter. so you can see below the google captcha code form Validation with Codeigniter 4.
Overview
Step 1: Download Codeigniter
Step 2: Basic Configurations
Step 3: Create a Database in table
Step 4: Connect to Database
Step 5: Get and Set Google Captcha Secrets
Step 6: Create Controller and Model
Step 7: Create Views Files
Step 8: Run The Application
Step 1: Download Codeigniter
If you want to download or install the latest version of CodeIgniter 4 then you can go to Codeigniter’s official site and download the latest version of Codeigniter 4. after the downloaded you can configure in “xampp/htdocs/” directory.
Step 2: Basic Configurations
If you want to Basic Configurations in your project then you can below Url.
Codeigniter 4 Removing Index.Php From Url
Step 3: Create a Database in table
In this step, We will create the database and table.
1 2 3 4 5 6 7 8 9 | CREATE TABLE IF NOT EXISTS `students` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(64) NOT NULL, `last_name` varchar(64) NOT NULL, `address` text NOT NULL, `email` varchar(64) NOT NULL, `mobile` varchar(12) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ; |
Step 4: Connect to Database
Go to the “app/Config/Database.php” folder and open the database.php file some changes in this file like hostname, database username, database password, and database name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'codeigniter4_jqurey_validation', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'production'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ]; |
Step 5: Get and Set Google Captcha Secrets
First, we need to Google reCAPTCHA site key and secret key. so first we go to Google reCAPTCHA panel and get site key and secret key.
After getting the key, we will create a form using the bootstrap and pass the site key.
When the user fills the form data with resolves the reCAPTCHA code that time response token will be returned.
Step 6: Create Controller and Model
In this step, we will create the “Student.php” controller and the “StudentModel.php” model.
app/Controllers/Student.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | <?php namespace App\Controllers; use CodeIgniter\Controller; use App\Models\StudentModel; class Student extends Controller { public function __construct() { helper(['form', 'url']); } public function index() { return view('add'); } public function store() { $rules = [ 'txtFname' => 'required', 'txtLname' => 'required', 'txtEmail' => 'required|valid_email', 'txtMobile' => 'required|min_length[10]|numeric', 'txtAddress' => 'required' ]; if (!$this->validate($rules)) { return view('add', ['validation' => $this->validator]); } else { $recaptchaResponse = trim($this->request->getVar('g-recaptcha-response')); $userIp=$this->request->ip_address(); $secret='ENTER_YOUR_SECRET_KEY'; $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$recaptchaResponse."&remoteip=".$userIp), true); if($response['success'] == false) { $session->setFlashdata('msg', 'Something goes to wrong'); } else { $data = [ 'first_name' => $this->request->getVar('txtFname'), 'last_name' => $this->request->getVar('txtLname'), 'email' => $this->request->getVar('txtEmail'), 'mobile' => $this->request->getVar('txtMobile'), 'address' => $this->request->getVar('txtAddress'), ]; $model = new StudentModel(); $save = $model->insert($data); $session->setFlashdata('msg', 'Form has been successfully submitted'); } return redirect()->to( base_url('student') ); } } } ?> |
app/Models/StudentModel.php
1 2 3 4 5 6 7 8 9 10 11 12 | <?php namespace App\Models; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Model; class StudentModel extends Model { protected $table = 'Students'; protected $allowedFields = ['first_name','last_name','address','email', 'mobile']; } ?> |
Step 7: Create Views Files
Finally, we will create the add.php in the app/views directory.
app/views/add.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <!DOCTYPE html> <html> <head> <title>Codeigniter 4 Google ReCaptcha V2 Example Tutorial - XpertPhp</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-9"> <h2>Add Student</h2> </div> </div> <div class="row"> <div class="col-md-9"> <?= \Config\Services::validation()->listErrors(); ?> <form method="post" name="frmAddStudent" id="frmAddStudent" action="<?php echo site_url('student/store');?>" enctype="multipart/form-data"> <div class="form-group"> <label for="txtFname">First Name</label> <input type="text" name="txtFname" class="form-control" id="txtFname" placeholder="Please enter first name" /> </div> <div class="form-group"> <label for="txtLname">Last Name</label> <input type="text" name="txtLname" class="form-control" id="txtLname" placeholder="Please enter last name" /> </div> <div class="form-group"> <label for="txtEmail">Email</label> <input type="text" name="txtEmail" class="form-control" id="txtEmail" placeholder="Please enter email" /> </div> <div class="form-group"> <label for="txtMobile">Mobile</label> <input type="text" name="txtMobile" class="form-control" id="txtMobile" placeholder="Please enter mobile number." /> </div> <div class="form-group"> <label for="txtAddress">Address</label> <textarea name="txtAddress" class="form-control"></textarea> </div> <div class="form-group"> <div class="g-recaptcha" data-sitekey="here_enter_site_key"></div> </div> <div class="form-group"> <input type="submit" value="Add" name="btnadd" id="btnadd" class="btn btn-success" /> </div> </form> </div> </div> <span class="d-none alert alert-success mb-3" id="res_message"></span> </div> </body> </html> |
Step 8: Run The Application
We can start the server and run the codeigniter 4 application using the below command.
1 | php spark serve |
Now we will run our example using the below Url in the browser.
1 | http://localhost:8080/student |
If you liked this article, you can also download it through our Github Repository.