Codeigniter PHP Google Recaptcha Form Validation Demo

In this php codeigniter google reCaptcha validation tutorial, we would to share with you how to integrate google reCaptcha validation using Google apis with php codeigniter. Here you will learn how to stop spaming for making your forms with google captcha.

Google reCaptcha form validation process to protect your website from spam and abuse.

We will integrate google reCaptcha with codeigniter form. Here you will learn google reCaptcha form validation with php codeigniter step by step. We will provide a demo example at the end of this article.

Codeigniter Google reCaptcha

Contents

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Generate reCaptcha Key & Secret
  • Make New Controller
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo/';

Create Database With Table

In this step, we need to create database name demo, so let’s open your phpmyadmin and create the database with the name demo . After successfully create a database, you can use the below sql query for creating a table in your database. We will add some cities with city info.

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;

Setup Database Credentials

In this step, We need to connect our project to database. we need to go application/config/ and open database.php file in text editor. After open the file in text editor, We need to setup database credential in this file like below.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'demo',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Generate reCaptcha Key & Secret

Now we will create new Google reCaptcha key and secret for our application. Follow all the below steps for creating google reCaptcha key or secret. Click here for creating a google reCaptcha key or secret. When you will click the given link, the below form open in your browser. Now fill this form and get your key and secret.

Google reCaptcha php Codeigniter

You will submit the above form after that you will be get google reCaptcha secret_site and secret_key.

google recaptcha

Create Controller

Now we need to create a controller name Google.php. In this controller we will create some method/function. We will build some of the methods like :

  • Index() – This is used to show the google recaptcha form
  • Store() – Store method is used to store validate data into database
  • Put key – In this controller you will put also “ENTER_YOUR_SECRET_KEY” .
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Google extends CI_Controller {

    public function __construct() {
        parent::__construct();
		// load model
        $this->load->helper(array('url','form'));
        $this->load->library('session');
        $this->load->database();
    }    

    public function index(){
      $this->load->view('google_recaptcha');
    }
 
    public function googleCaptachStore(){
      
      $data = array('name' => $this->input->post('name'),
                    'email' => $this->input->post('email'), 
                    'mobile_number' => $this->input->post('mobile_number'), 
                   );
      
      $recaptchaResponse = trim($this->input->post('g-recaptcha-response'));
      
      $userIp=$this->input->ip_address();
        
      $secret='ENTER_YOUR_SECRET_KEY';
      
      $credential = array(
            'secret' => $secret,
            'response' => $this->input->post('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']){ 
       $this->db->insert('users',$data); 
       $this->session->set_flashdata('message', 'Google Recaptcha Successful');
      }else{
       $this->session->set_flashdata('message', 'Sorry Google Recaptcha Unsuccessful!!');
      }
      redirect(base_url('google'));
     }

}
?>

Create Views

Now we need to create google_catpcha.php, go to application/views/ folder and create google_catpcha .php file. Here put the below html code into google_recaptcha.php file.

We will also put the YOUR_SITE_KEY in this file, like this ==>

<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>  
<!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 - Tutsmake.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('message')?></strong></div>
    <br>
    <br>
    <div class="row">
    <div class="col-md-9">
    <form  method="post" action="<?php echo base_url('google/googleCaptachStore') ?>">
      <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>

In this script code, we have intialize the google line and bar charts with php codeigniter and set the data on it.

Start Development server

For start development server, Go to the browser and hit below the url.

http://localhost/demo/google

Conclusion

In this codeigniter google reCaptcha validation tutorial, We have successfully created a form for showing captcha validation and also we have to call the google api for validating a captcha, after successfully validate a google captcha, we will do next process.

If you have any questions or thoughts to share, use the comment form below to reach us.

Spread the love

Be First to Comment

Leave a Reply

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