Example – Captcha in CodeIgniter using Captcha Helper


A CAPTCHA (Complete Automated Public Turning test to tell Computer and Human Apart) is a type of challenge test to identify whether the user is human or not. Captcha mostly used in all web application to protect the website from getting spammed. A captcha is very important where any input is given from user or any action is processed based on the user response.

CAPTCHA is randomly generated string incorporated in an image file which is display to the user and the random string is stored in SESSION variable. Once the user submits the captcha word by viewing captcha image, the submitted value will be compare with the session value. If both the captcha code is matched, further action should take.

In this tutorial, we’ll demonstrate how to implement captcha in CodeIgniter. CodeIgniter provides a captcha helper to create CAPTCHA. CodeIgniter CAPTCHA Helper helps to generate captcha image with customization options. Here we’ll provide the example code to implement captcha functionality in CodeIgniter.

  • Create and display captcha image.
  • Get user input and submit for comparison.
  • Compare user input with captcha word and return the status.

The following code is used to create captcha in CodeIgniter.

You can use a different font for captcha word by specifying font_path value in captcha configuration array.

Controller (Captcha.php)

To using the CodeIgniter captcha helper, you need to load captcha helper which is included in __construct() function.
index() function creates captcha, pass the captcha image to view, and load the respective view. Also, handles the captcha submission and comparison process.
refresh() function is used when the user request for a new captcha.

View (captcha/index.php)

Initially, the view file is loaded with captcha image, refresh image, input field, and submit button. Once the user submits the captcha word it will be sent to the index() method of Captcha controller for comparison.

Also, the user can request for a new captcha image by refresh link. An ajax script would run on refresh link click, then new captcha image is fetched from the refresh() method of Captcha controller and replace the captcha image with new image.


Leave A Reply

Your email address will not be published.