Out of the box, CodeIgniter has a good CAPTCHA helper to use in your web applications. Here is a simple example of how to get a new CAPTCHA image without having to reload the page 😉
Basic Controller
class Welcome extends CI_Controller { private $captcha_path = 'assets/img/captcha/'; public function __construct() { parent::__construct(); } public function index() { $this->load->helper(array('captcha')); $captcha = create_captcha(array( 'word' => strtoupper(substr(md5(time()), 0, 6)), 'img_path' => $this->captcha_path, 'img_url' => $this->captcha_path )); $data = array( 'captcha' => $captcha ); $this->session->set_userdata('captcha', $captcha['word']); $this->load->view('welcome', $data); } }
The View (jQuery used for UI buttons and altering CAPTCHA image ‘src’ attribute)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/blitzer/jquery-ui.css">
<script>
$(function(){
$('#new_captcha').button({
text: false,
icons: {
primary: 'ui-icon-refresh'
}
}).click(function(event){
event.preventDefault();
$(this).prev().attr('src', 'welcome/new_captcha?'+Math.random());
});
});
</script>
<?php echo $captcha['image']; ?>
<a href="#" id="new_captcha">Reload CAPTCHA</a>
Modified Controller Continue reading