azazqadir azazqadir - 8 months ago
822 0

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.

In this tutorial, I will demonstrate how you can easily implement CAPTCHA in your CodeIgniter projects.

Read: Captcha in CodeIgniter

PHP

CodeIgniter Captcha

<?php

defined('BASEPATH') OR exit('your exit message');

class Captcha extends CI_Controller

{

   function __construct()

   {

       parent::__construct();

       $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'];

   }

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download