In this tutorial, I will demonstrate how you can easily implement CAPTCHA in your CodeIgniter projects built on any hosting for PHP.
CAPTCHA is a randomly generated string (or a set of images) that appears when verification is required. It is an essential requirement for cutting down the spam at a website. In many cases, it is the only line of defense a website has against bots that spam websites.
Create Controller
The process starts with the creation of the Controller.
Create a file named captcha.php in the Controller folder. Open the file in your code editor and add the following code to it:
<?php defined('BASEPATH') OR exit('your exit message'); class Captcha extends CI_Controller {function __construct(){ parent::__construct(); $this->load->library('session'); $this->load->helper('captcha'); } public function index(){ if ($this->input->post('submit')) { $captcha_insert = $this->input->post('captcha'); $contain_sess_captcha = $this->session->userdata('valuecaptchaCode'); if ($captcha_insert === $contain_sess_captcha) { echo 'Success'; } else { echo 'Failure'; } } $config = array( 'img_url' => base_url() . 'image_for_captcha/', 'img_path' => 'image_for_captcha/', 'img_height' => 45, 'word_length' => 5, 'img_width' => '45', 'font_size' => 10 ); $captcha = create_captcha($config); $this->session->unset_userdata('valuecaptchaCode'); $this->session->set_userdata('valuecaptchaCode', $captcha['word']); $data['captchaImg'] = $captcha['image']; $this->load->view('captcha/index', $data); } public function refresh() { $config = array( 'img_url' => base_url() . 'image_for_captcha/', 'img_path' => 'image_for_captcha/', 'img_height' => 45, 'word_length' => 5, 'img_width' => '45', 'font_size' => 10 ); $captcha = create_captcha($config); $this->session->unset_userdata('valuecaptchaCode'); $this->session->set_userdata('valuecaptchaCode', $captcha['word']); echo $captcha['image']; } }
Code Explanation
Here is a brief explanation of the various components of the Controller code:
Load CAPTCHA Helper Â
$this->load->helper('captcha');
Form Submission
if ($this->input->post('submit')) { Â Â Â Â Â Â Â Â Â Â Â $captcha_insert = $this->input->post('captcha'); Â Â Â Â Â Â Â Â Â Â Â $contain_sess_captcha = $this->session->userdata('valuecaptchaCode'); Â Â Â Â Â Â Â Â Â Â Â if ($captcha_insert === $contain_sess_captcha) { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â echo 'Success'; Â Â Â Â Â Â Â Â Â Â Â } else { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â echo 'Failure'; Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â }
Stop Wasting Time on Servers
Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.
CAPTCHA Configuration
'img_url' => base_url() . 'image_for_captcha/', Â Â Â Â Â Â Â Â Â Â Â 'img_path' => 'image_for_captcha/', Â Â Â Â Â Â Â Â Â Â Â 'img_height' => 45, Â Â Â Â Â Â Â Â Â Â Â 'word_length' => 5, Â Â Â Â Â Â Â Â Â Â Â 'img_width' => '45', Â Â Â Â Â Â Â Â Â Â Â 'font_size' => 10
Refresh CAPTCHA
public function refresh()    {        $config = array(            'img_url' => base_url() . 'image_for_captcha/',            'img_path' => 'image_for_captcha/',            'img_height' => 45,            'word_length' => 5,            'img_width' => '45',            'font_size' => 10        );        $captcha = create_captcha($config);        $this->session->unset_userdata('valuecaptchaCode');        $this->session->set_userdata('valuecaptchaCode', $captcha['word']);        echo $captcha['image'];    } Unset Previous CAPTCHA and Set a New One $this->session->unset_userdata('valuecaptchaCode'); $this->session->set_userdata('valuecaptchaCode', $captcha['word']); Load the View    $this->load->view('captcha/index', $data);
You might also like:Â How To Host CodeIgniter
Create the View
The next step is the creation of the View. for this, create a folder in the View folder. Go into the folder and create another folder with the name captcha. inside this folder, create a file named index.php. Add the following code to the file:
<!DOCTYPE html> <html> <head> Â Â Â <title>Implement Captcha in Codeigniter using helper</title> Â Â Â <script> Â Â Â Â Â Â Â $(document).ready(function(){ Â Â Â Â Â Â Â Â Â Â Â $('.captcha-refresh').on('click', function(){ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â $.get('<?php echo base_url().'captcha/refresh'; ?>', function(data){ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â $('#image_captcha').html(data); Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }); Â Â Â Â Â Â Â Â Â Â Â }); Â Â Â Â Â Â Â }); Â Â Â </script> Â Â Â <script src="<?php echo base_url(); ?>/js/jquery.js"></script> </head> <body> <p id="image_captcha"><?php echo $captchaImg; ?></p> <a href="javascript:void(0);" class="captcha-refresh" ><img src="<?php echo base_url().'images/refresh.png'; ?>"/></a> <form method="post"> Â Â Â <input type="text" name="captcha" value=""/> Â Â Â <input type="submit" name="submit" value="SUBMIT"/> </form> </body> </html>
You Might Also Like: Learn to Implement CodeIgniter Form ValidationÂ
Another Method of Calling CAPTCHA in CodeIgniter with Validation
Here is another method that is used to call in CAPTCHA through CodeIgniter helper and then validate it.
<?php class Captcha extends CI_Controller { Â Â Â public function index() Â Â Â { Â Â Â Â Â Â Â $this->load->helper(array('form', 'url', 'captcha')); Â Â Â Â Â Â Â $this->load->library('form_validation'); Â Â Â Â Â Â Â $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); Â Â Â Â Â Â Â $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); Â Â Â Â Â Â Â $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database'); Â Â Â Â Â Â Â $this->form_validation->set_rules('captcha', 'Captcha', 'callback_validate_captcha'); Â Â Â Â Â Â Â if ($this->form_validation->run() == FALSE) { Â Â Â Â Â Â Â Â Â Â Â $original_string = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z')); Â Â Â Â Â Â Â Â Â Â Â $original_string = implode("", $original_string); Â Â Â Â Â Â Â Â Â Â Â $captcha = substr(str_shuffle($original_string), 0, 6); Â Â Â Â Â Â Â Â Â Â Â $vals = array( Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'word' => $captcha, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'img_path' => 'image_for_captcha/', Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'font_size' => 10, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'img_width' => 150, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'img_height' => 50, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'expiration' => 7200 Â Â Â Â Â Â Â Â Â Â Â ); Â Â Â Â Â Â Â Â Â Â Â $cap = create_captcha($vals); Â Â Â Â Â Â Â Â Â Â Â $data['image'] = $cap['image']; Â Â Â Â Â Â Â Â Â Â Â if (file_exists(BASEPATH . "../captcha/" . $this->session->userdata['image'])) Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â unlink(BASEPATH . "../captcha/" . $this->session->userdata['image']); Â Â Â Â Â Â Â Â Â Â Â $this->session->set_userdata(array('captcha' => $captcha, 'image' => $cap['time'] . '.jpg')); Â Â Â Â Â Â Â Â Â Â Â $this->load->view('index_index', $data); Â Â Â Â Â Â Â } else { Â Â Â Â Â Â Â Â Â Â Â if (file_exists(BASEPATH . "../captcha/" . $this->session->userdata['image'])) Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â unlink(BASEPATH . "../captcha/" . $this->session->userdata['image']); Â Â Â Â Â Â Â Â Â Â Â $this->session->unset_userdata('captcha'); Â Â Â Â Â Â Â Â Â Â Â $this->session->unset_userdata('image'); Â Â Â Â Â Â Â Â Â Â Â redirect('home', 'refresh'); Â Â Â Â Â Â Â } Â Â Â } Â Â Â public function validate_captcha() Â Â Â { Â Â Â Â Â Â Â if ($this->input->post('captcha') != $this->session->userdata['captcha']) { Â Â Â Â Â Â Â Â Â Â Â $this->form_validation->set_message('validate_captcha', 'Cpatcha Code is wrong'); Â Â Â Â Â Â Â Â Â Â Â return false; Â Â Â Â Â Â Â } else { Â Â Â Â Â Â Â Â Â Â Â return true; Â Â Â Â Â Â Â } Â Â Â } }
You might also like:Â How To Pass Data From Controller To View In CodeIgniter
Conclusion
In this tutorial, I discussed how you could easily integrate CAPTCHA into CodeIgniter projects. If you need help. just drop a comment and I will get back to you.
Owais Khan
Owais works as a Marketing Manager at Cloudways (managed hosting platform) where he focuses on growth, demand generation, and strategic partnerships. With more than a decade of experience in digital marketing and B2B, Owais prefers to build systems that help teams achieve their full potential.