Invisible reCAPTCHA with CodeIgniter

This post explains on creating a CodeIgniter library for using the Invisible reCAPTCHA on forms.

Using the invisible reCAPTCHA with CodeIgniter is very easy. We will create a simple CodeIgniter library and then use it in the controllers. First we will go through the generic invisible reCAPTCHA process.

Generic invisible reCAPTCHA process

  1. First you will register your domain for the reCaptcha by visiting to https://www.google.com/recaptcha/admin and you will receive a website key and a secret key.
  2. In the webpage you will include the reCaptcha JavaScript file before closing the head tag.
    <script src='https://www.google.com/recaptcha/api.js'></script>
  3. Then include button to submit the form with below data attributes. As part of the attribute you will give a name to a call back function which you will use to to submit the form.
    <button
              class="g-recaptcha"
              data-sitekey="XXXXXXX-Your Site-Key-XXXXX"
              data-callback="SubmitForm">
                        Submit
    </button>
    <script>
    function SubmitForm(){
              document.forms[0].submit();
    }
    </script>
  4. In server side you will receive the reCaptcha response in POST variable named "g-recaptcha-response" which you need to pass to the server with your secret key to validate whether the response is valid.
  5. If the response is valid you can process the form otherwise can display the error message to the user indicating the validation failure.

Implementing invisible reCaptcha using CodeIgniter

  1. First create a file named Recaptcha.php inside the application/library folder of your CodeIgniter website. 
    
    <?php
    /**
     *
     * @package    CodeIgniter/Recaptcha
     * @category   Provider
     * @author     Sivapatham Nishanthan
     * @copyright  (c) 2017 ThePHPCode.com
     * @license    MIT License
     */
    class Recaptcha {
        private $secret;
        private $url;
        private $CI;
        public function __construct() {
            $this->CI = & get_instance();
            $this->CI->load->config('recaptcha');
            $this->CI->load->config('recaptcha');
            $this->secret = $this->CI->config->item('secret_key');
            $this->url = $this->CI->config->item('verify_url');
        }
    
        public function is_valid($response='',$ip="") {
            if($response==''){
                $response = $this->CI->input->post('g-recaptcha-response');
            }
            $ch = curl_init();
    
            curl_setopt($ch, CURLOPT_URL, $this->url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
            curl_setopt($ch, CURLOPT_POSTFIELDS,array(
                'secret'=>  $this->secret,
                'response'=>$response,
                'remoteip'=>$ip
            ) );
    
            $result_ = curl_exec($ch);
            curl_close($ch);
            $Result = json_decode($result_);
            if($Result->success == 'true'){
                return TRUE;
            } else{
                return FALSE;
            }
        }
    }
    
    
  2. Create a file named recaptcha.php inside the application/config directoy with following code.

    
    
    <?php 
    if ( ! defined('BASEPATH')) 
        exit('No direct script access allowed');
    
    $config['secret_key'] = '6LdqOScUAAAAALy-QqC9JXkHdg-Gdj4U4791CqxX';
    $config['site_key'] = '6LdqOScUAAAAAKGl6GzklEPvLy8etj3neHc7xkK4';
    $config['verify_url'] = 'https://www.google.com/recaptcha/api/siteverify';
    
    
    
  3. Call the library inside the controller function where you want to use the invisible reCAPTCHA. Below is an example controller function.
    
    function do_something() {
            $this->load->library("Form_validation");
            $this->form_validation->set_rules('field1', 'Field 1', 'trim|required');
            $this->form_validation->set_rules('field2', 'Field 2', 'trim|required');
    
            $this->form_validation->set_error_delimiters('</li><li>', '</li><li>');
    
            if ($this->form_validation->run() == TRUE) {
                $this->load->library('recaptcha');
                if (!$this->recaptcha->is_valid()) {
                    $data['message'] = array(
                        'type' => 'danger',
                        'message' => 'Form validation failed'
                    );
                    $this->load->view("my_view", $data);
                    return;
                }
                //Other processing
            } else{
               $data = array();
               $this->load->view("my_view", $data);           
            }
    }
    
    
  4. Have the following code in your form for generating the reCaptcha code at client side when submitting the form and to display the error message

    
    
    <html>
    <head>
    <script src='https://www.google.com/recaptcha/api.js'></script>
    </head>
    <title></title>
    <body>
    
    <script>
        function submitForm(){
            document.forms[0].submit();
        }
    </script>
    
    <?php 
    if (isset($message)) { ?>
        <div class="alert alert-<?php echo $message['type']; ?>">
            <?php echo $message['message']; ?>
        </div>
    <?php } ?>
    
    <div class="form-group">
        <label class="control-label col-md-3" for="field1">Field 1<span class="required">*</span> </label>
        <div class="col-md-3">
            <input class="form-control" name="field1" type="text" value="<?php echo set_value('field1'); ?>" />
        </div>
        <div class="col-md-6 text-danger"></div>
    </div>
    
    <div class="form-group">
        <label class="control-label col-md-3" for="field2">Field 2<span class="required">*</span> </label>
        <div class="col-md-3">
            <input class="form-control" name="field2" type="text" value="<?php echo set_value('field2'); ?>" />
        </div>
        <div class="col-md-6 text-danger"></div>
    </div>
    
    <button class="g-recaptcha btn btn-primary"  data-sitekey="YourSiteKey" data-callback="submitForm"> Submit </button>
    
    </body>
    </html>
    
    

Hope this quick tutorial helped you to implement the Invisible reCAPTCHA with CodeIgniter. Please share this if this was useful to you.

Generate your website

Do you know that the PHP Code Generator can generate PHP websites in minutes in CodeIgniter 3?

Learn more about our PHP Code Generator and generate your web applications using PCG with functioning admin portal.

Connect with Google or Facebook and generate your next CodeIgniter website in minutes with plenty of features like searching with pagination, AJAX based grid data editors, group based security and admin portal etc.