Registration form with google v2 recaptcha in codeigniter 4 example; In this tutorial, i will guide you step by step on how to implement registration form with google v2 recaptcha in codeigniter 4 app using google apis.
Note that google v2 or v3 reCAPTCHA protects your website from fraud and abuse.
If you are creating a form in codeigniter 4 app. And you want to protect your form with the help of Google v2 Recaptcha. So in this tutorial you will learn how to integrate Google v2 Recaptcha with your codeigniter 4 forms.
Before start this tutorial, you need to create google reCaptcha key or secret. Click here for creating a google reCaptcha key or secret.
Google ReCaptcha v2 Form in CodeIgniter 4 Example
- Install Codeigniter 4 Application
- Basic App Configurations
- Create Database And Table
- Connect App to Database
- Create Model & Controller Class
- Create Views
- Setup Routes
- Start Development server
Step 1 – Install Codeigniter 4 Application
First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .
Note that, please change the download folder name “demo”.
Step 2 – Basic App Configurations
Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
Step 3 – Create Database And Table
Create database and tables by executing the following query:
CREATE TABLE users ( id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key', name varchar(100) NOT NULL COMMENT 'Name', email varchar(255) NOT NULL COMMENT 'Email Address', contact_no varchar(50) NOT NULL COMMENT 'Contact No', created_at varchar(20) NOT NULL COMMENT 'Created date', PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
Step 4 – Connect App to Database
To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:
public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'test', 'password' => '4Mu99BhzK8dr4vF1', 'database' => 'demo', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'development'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ];
Step 5 – Create Model & Controller Class
Create UserModel.php file. So, visit app/Modelsdirectory and create UserModel.php.Then add the following code into it:
<?php namespace App\Models; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Model; class UserModel extends Model { protected $table = 'contacts'; protected $allowedFields = ['name', 'email']; }
Create GoogleReCaptcha.php file. So, visit app/Controllers directory and create GoogleReCaptcha.php.Then add the following code into it:
<?php namespace App\Controllers; use CodeIgniter\Controller; use CodeIgniter\HTTP\RequestInterface; use App\Models\UserModel; class GoogleReCaptcha extends Controller { public function index(){ return view('home'); } public function googleCaptach() { $model = new UserModel(); $data = array('name' => $this->request->getVar('name'), 'email' => $this->request->getVar('email'), 'contact_no' => $this->request->getVar('mobile_number'), ); $recaptchaResponse = trim($this->request->getVar('g-recaptcha-response')); $userIp=$this->request->ip_address(); $secret='ENTER_YOUR_SECRET_KEY'; $credential = array( 'secret' => $secret, 'response' => $this->request->getVar('g-recaptcha-response') ); $verify = curl_init(); curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify"); curl_setopt($verify, CURLOPT_POST, true); curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($credential)); curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($verify, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($verify); $status= json_decode($response, true); if($status['success']){ $model->save($data); $session->setFlashdata('msg', 'Form has been successfully submitted'); }else{ $session->setFlashdata('msg', 'Something goes to wrong'); } return redirect()->to('/'); } }
Step 6 – Create Views
Create home.php view file, so visit app/views/ directory and create home.php file. Then add the following HTML into list.php file:
<!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>Codeigniter Google Recaptcha Form Validation Example - laratutorials.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src='https://www.google.com/recaptcha/api.js'></script> <style> .error{ color:red; } </style> </head> <body> <div class="container"> <div class="error"><strong><?=$this->session->flashdata('msg')?></strong></div> <br> <br> <div class="row"> <div class="col-md-9"> <form method="post" action="<?php echo base_url('captcha-v2') ?>"> <div class="form-group"> <label for="formGroupExampleInput">Name</label> <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name"> </div> <div class="form-group"> <label for="email">Email Id</label> <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id"> </div> <div class="form-group"> <label for="mobile_number">Mobile Number</label> <input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number" maxlength="10"> </div> <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div> <div class="form-group"> <button type="submit" id="send_form" class="btn btn-success">Submit</button> </div> </form> </div> </div> </div> </body> </html>
Step 7 – Setup Routes
To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:
// $routes->setDefaultController('GoogleReCaptcha'); $routes->get('/', 'GoogleReCaptcha::index'); $routes->post('captcha-v2', 'GoogleReCaptcha::googleCaptach');
Step 8 – Start Development server
Execute the following command into command prompt or terminal to start the codeigniter 4 application:
php spark serve
Then visit your web browser and hit the following url on it:
http://localhost/demo/ OR http://localhost:8080/
Conclusion
Registration form with google v2 recaptcha in codeigniter 4 example; In this tutorial, you have learned how to implement registration form with google v2 recaptcha in codeigniter 4 app using google apis.
Recommended CodeIgniter 4 Tutorial
- How to Install / Download Codeigniter 4 By Manual, Composer, Git
- How to Remove Public and Index.php From URL in Codeigniter 4
- Codeigniter 4 – Form Validation Example Tutorial
- How to add jQuery Validation on Form in Codeigniter 4 Example
- Codeigniter 4 Ajax Form Submit Validation Example
- Codeigniter 4 File Upload Validation Example
- Image Upload with Validation in Codeigniter 4
- Codeigniter 4 Image Upload Preview Using jQuery Example
- Codeigniter 4 Ajax Image Upload Preview Example
- How to Upload Multiple Images in Codeigniter 4
- Codeigniter 4 Multiple Image Upload with Preview
- Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
- Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
- Codeigniter 4 CRUD with Datatables Example
- Codeigniter 4 Image Crop and Save using Croppie Example
- Codeigniter 4 Dependent Dropdown using jQuery Ajax Example
- CodeIgniter 4 Rest Api CRUD Example
- Codeigniter 4 Login Registration and Logout Example
- Codeigniter 4 – Get Address from Latitude and Longitude Ex
- Codeigniter 4 Google Column Charts Example
- Codeigniter 4 Ajax Load More Data on Page Scroll