How to use Captcha in CodeIgniter?

In this tutorial, I will show you integrating Captcha in your CodeIgniter application. We gonna use CI’s builtin captcha helper and contains functions that assist in creating CAPTCHA images. This helper needs GD library installed on your server.

How to use Captcha in CodeIgniter

Here are the steps to use Captcha helper in the CodeIgniter 3 application forms:

Download and Install

Step 1: Download from the official website and install CodeIgniter.

Create Controller

Step 2: Lets create a contoller called captcha.php with below code in application/controllers/captcha.php.

The _generateCaptcha() method will generate captcha image and will place generated image inside captcha_images directory as configurated and you must create captcha_images directory in your codeigniter project root directory and change its permission to 777 or 666.

Create a form

Step 2: Crate a View file called captcha_view.php in the applications/views/captcha_view.php

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

8 Comments

        1. In the above example we had created captcha images with 7200 time of expiration. so you don’t need to worry , captcha_helpler will automatically delete all the expired images while creating new captcha images.

        2. if you want to delete it every time, just check out this

          in the above controller

          before this line : $this->session->unset_userdata(‘captchaWord’);

          add this lines :

          /* delete captcha file */
          $this->deleteOldCaptcha(‘./dcaptcha/’.$this->session->userdata(‘captchaName’).’.jpg’);
          $this->session->unset_userdata(‘captchaName’);

          and in the validation failed case also we need to clear the image, so add the in the else block

          if($this->session->userdata(‘captchaName’)){
          $this->deleteOldCaptcha(‘./dcaptcha/’.$this->session->userdata(‘captchaName’).’.jpg’);
          }

          Final step add

          $this->session->set_userdata(‘captchaName’, $captcha[‘time’]);

          this after

          $this->session->set_userdata(‘captchaWord’, $captcha[‘word’]);

          Add this method in your controller :
          private function deleteOldCaptcha($filename) {
          if(is_readable($filename) && unlink($filename)) {
          return TRUE;
          }
          }

Leave a Reply

Your email address will not be published.