Hello, I'm Erwin. I'm a Web Developer.
See my little experiences on my blog.

Create Simple Captcha on Code Igniter

Posted: May 1st, 2010 | Author: erwin | Filed under: PHP | Tags: , | No Comments »

Hello, there.. In this post, I would like to explain how to create simple captcha in Code Igniter. Basic on this captcha is generate random code, save it to session, and check post code with session. If the post code is match then return TRUE and vice versa.

First create validation function on your form controller.

function captcha_check($str)

{

//check captcha

$get_false=FALSE;

if (strtolower(trim($this->session->userdata(“captcha”)))!=strtolower(trim($str)))

{

$get_false = TRUE;

$this->form_validation->set_message(‘captcha_check’, ‘Wrong code, please type again!’.$this->session->userdata(“captcha”));

return FALSE;

}

if ($get_false==FALSE)

{

return TRUE;

}

}

Then set you form captcha validation and put callback_captcha_check on validation rules.
//form validation
$config = array(
array(
‘field’ => ‘captcha’,
‘label’ => ‘Captcha’,
‘rules’ => ‘trim|required|callback_captcha_check’
)
);
$this->form_validation->set_rules($config);
Next create random string on your view and save it into session.
<?php   $listAlpha = ‘abcdefghijklmnopqrstuvwxyz0123456789′;
$numAlpha=6;
$captcha=substr(str_shuffle($listAlpha),0,$numAlpha);
$code_captcha = array(
‘captcha’ => $captcha,
);
$this->session->set_userdata($code_captcha);
?>
The show the random string into your form and let user type the code on input form.