How to Integrate Google reCAPTCHA in CodeIgniter Form Validation (v3 & v4)

Last updated 2 weeks, 5 days ago | 34 views 75     5

Google reCAPTCHA is one of the most effective tools to protect your forms from bots and spam. If you're building forms in CodeIgniter, integrating reCAPTCHA helps improve security without compromising the user experience.

This article walks you through integrating Google reCAPTCHA (v2 or v3) into your CodeIgniter application, step-by-step.


What is Google reCAPTCHA?

Google reCAPTCHA helps you verify that a human, not a bot, is interacting with your form. There are two common versions:

  • v2 Checkbox: "I'm not a robot" checkbox.

  • v3 Invisible: Uses scoring without user interaction.

We’ll use reCAPTCHA v2 Checkbox in this example (easiest to integrate).


Step-by-Step: Google reCAPTCHA Integration in CodeIgniter


✅ Step 1: Register on Google reCAPTCHA Admin Console

  • Go to: https://www.google.com/recaptcha/admin

  • Register a new site

    • Choose reCAPTCHA v2 → "I'm not a robot" checkbox

    • Enter domain (e.g., localhost, example.com)

  • You’ll get:

    • Site Key (for frontend)

    • Secret Key (for backend)


✅ Step 2: Add reCAPTCHA to Your HTML Form

<!-- application/views/form_view.php -->
<form action="<?= base_url('form/submit') ?>" method="post">
    <input type="text" name="name" placeholder="Your Name" required><br><br>

    <!-- Google reCAPTCHA widget -->
    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY_HERE"></div><br>

    <input type="submit" value="Submit">
</form>

<!-- Load reCAPTCHA API -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

✅ Step 3: Create Controller and Validate reCAPTCHA Server-side

// application/controllers/Form.php
class Form extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library(['form_validation']);
    }

    public function index() {
        $this->load->view('form_view');
    }

    public function submit() {
        // Validate form fields
        $this->form_validation->set_rules('name', 'Name', 'required');
        $this->form_validation->set_rules('g-recaptcha-response', 'reCAPTCHA', 'callback_verify_recaptcha');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('form_view');
        } else {
            echo "Form submitted successfully and reCAPTCHA verified!";
        }
    }

    // reCAPTCHA validation callback
    public function verify_recaptcha($response) {
        $secret_key = 'YOUR_SECRET_KEY_HERE';
        $verify_url = 'https://www.google.com/recaptcha/api/siteverify';

        $responseData = file_get_contents($verify_url . '?secret=' . $secret_key . '&response=' . $response);
        $result = json_decode($responseData, true);

        if (isset($result['success']) && $result['success'] === true) {
            return TRUE;
        } else {
            $this->form_validation->set_message('verify_recaptcha', 'Please verify that you are not a robot.');
            return FALSE;
        }
    }
}

Full Working Example

Folder Structure:

application/
├── controllers/
│   └── Form.php
├── views/
│   └── form_view.php

Replace with Your Keys:

  • YOUR_SITE_KEY_HERE in the view

  • YOUR_SECRET_KEY_HERE in the controller


Tips

  1. Always validate reCAPTCHA server-side — never rely on the frontend only.

  2. ✅ Use curl instead of file_get_contents() if your server doesn't allow remote file_get_contents() calls:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $verify_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'secret' => $secret_key,
        'response' => $response
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($result, true);
    
  3. ✅ Style the reCAPTCHA widget to fit your form design using CSS if needed.

  4. ✅ If using CodeIgniter 4, use similar logic in app/Controllers and call $this->request->getPost('g-recaptcha-response').


⚠️ Common Pitfalls

  • Using incorrect site/secret key pair: Always use the correct key for your domain.

  • Missing reCAPTCHA script tag: If not loaded, the widget won't render.

  • Forgetting callback in form validation: reCAPTCHA won't be validated unless explicitly added with callback_verify_recaptcha.

  • Disabling allow_url_fopen: If disabled, file_get_contents() won’t work — switch to cURL.


Bonus: CI Helper for reCAPTCHA

You can abstract verification into a helper:

// application/helpers/recaptcha_helper.php
function verify_google_recaptcha($response) {
    $secret_key = 'YOUR_SECRET_KEY_HERE';
    $verify_url = 'https://www.google.com/recaptcha/api/siteverify';
    $responseData = file_get_contents($verify_url . '?secret=' . $secret_key . '&response=' . $response);
    $result = json_decode($responseData, true);
    return $result['success'] ?? false;
}

And in controller:

if (!verify_google_recaptcha($this->input->post('g-recaptcha-response'))) {
    // handle error
}

Conclusion

Integrating Google reCAPTCHA into your CodeIgniter forms adds a critical layer of protection against spam and bots. By verifying the token server-side and using CodeIgniter's validation system, you ensure that only real users can submit your forms.