Implement CAPTCHA In CodeIgniter

Implement CAPTCHA In CodeIgniter

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.CAPTCHA in CodeIgniterIn this tutorial, I will demonstrate how you can easily implement CAPTCHA in your CodeIgniter projects.

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:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899load->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 ExplanationHere is a brief explanation of the various components of the Controller code:Load CAPTCHA Helper  1$this->load->helper('captcha');Form Submission1234567891011121314151617if ($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';            }        }CAPTCHA Configuration1234567891011'img_url' => base_url() . 'image_for_captcha/',            'img_path' => 'image_for_captcha/',            'img_height' => 45,            'word_length' => 5,            'img_width' => '45',            'font_size' => 10Refresh CAPTCHA123456789101112131415161718192021222324252627282930313233343536373839public 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);

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:1234567891011121314151617181920212223242526272829303132333435363738394041424344454647      Implement Captcha in Codeigniter using helper           

  
         
  Another Method of Calling CAPTCHA with ValidationHere is another method that is used to call in CAPTCHA through CodeIgniter helper and then validate it.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697load->helper(array('form', 'url', 'captcha'));        $this->load->library('form_validation');        $this->form_validation->set_error_delimiters('
', '
');        $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;        }    } }

Conclusion

In this tutorial, I discussed how you could easily integrate CAPTCHA into your CodeIgniter projects. If you need help. just drop a comment and I will get back to you.