How to create captcha in CodeIgniter?

Creating a CAPTCHA in CodeIgniter can be done using the built-in CAPTCHA helper. Here are the steps to create a CAPTCHA in CodeIgniter:

Load the CAPTCHA helper in your controller:


Create an array of CAPTCHA configuration options. This includes the width and height of the image, the font size, the length of the CAPTCHA text, and the path to the font file.

$config = array(
   'img_path'      => './captcha/',
   'img_url'       => base_url().'captcha/',
   'img_width'     => '150',
   'img_height'    => 50,
   'word_length'   => 4,
   'font_size'     => 20,
   'font_path'     => FCPATH . 'path/to/font/file.ttf',
   'img_id'        => 'Imageid',
   'pool'          => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
   'expiration'    => 7200

Generate the CAPTCHA image and store the CAPTCHA text in a session variable using the create_captcha() function.

$captcha = create_captcha($config);
$this->session->set_userdata('captcha_text', $captcha['word']);

Pass the CAPTCHA image data to your view to display the image on the form.

$data['captcha_img'] = $captcha['image'];
$this->load->view('captcha_form', $data);

In your form, include an input field for the user to enter the CAPTCHA text.

   <img src="<?php echo $captcha_img; ?>" alt="CAPTCHA image">
   <input type="text" name="captcha" placeholder="Enter the text">
   <input type="submit" value="Submit">

In your form submission function, validate the user's input against the stored CAPTCHA text.

if ($this->input->post('captcha') == $this->session->userdata('captcha_text')) {
    // CAPTCHA text is correct, continue with form processing
} else {
    // CAPTCHA text is incorrect, show error message

And that's it, you have implemented a captcha feature in your codeigniter application. Keep in mind that the CAPTCHA images can be generated with different ways, you can use libraries like "google reCAPTCHA" or "math CAPTCHA" instead of the built-in CAPTCHA helper.


Added  Jan 26, 02:39 am

SignUp with Email