How to use Codeigniter captcha plug-in Part 2

DOWN LOAD
In the previous post I wrote a basic method how to use captcha plug-in with Codeigniter.
Today I am going to write a simple but practical newsletter subsciption page using captcha.
We will use CI’s form_validation class.

ci_captcha

Please read the previous post to customize it.
You need to create a folder called captcha as the same level as system.

Database

We need two tables, captcha and subscribers.


CREATE TABLE IF NOT EXISTS `captcha` (
  `captcha_id` bigint(13) unsigned NOT NULL AUTO_INCREMENT,
  `captcha_time` int(10) unsigned NOT NULL,
  `ip_address` varchar(16) NOT NULL DEFAULT '0',
  `word` varchar(20) NOT NULL,
  PRIMARY KEY (`captcha_id`),
  KEY `word` (`word`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;

CREATE TABLE IF NOT EXISTS `subscribers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ;

Config

config/autoload.php

$autoload['libraries'] = array('database', 'session');

$autoload['helper'] = array('url');

You can autoload library(form_validation) here as well.

Model

The code is from a Codeigniter book Professional CodeIgniter by Thomas Myer.

models/msubscribers.php

<?php

class MSubscribers extends Model{

	function MSubscribers(){
		parent::Model();
	}

function getSubscriber($id){
    $this->db->where('id',$id);
    $this->db->limit(1);
    $Q = $this->db->getwhere('subscribers');
    if ($Q->num_rows() > 0){
      $data = $Q->row_array();
    }

    $Q->free_result();
    return $data;
 }

 function getAllSubscribers(){
     $data = array();
     $Q = $this->db->get('subscribers');
     if ($Q->num_rows() > 0){
       foreach ($Q->result_array() as $row){
         $data[] = $row;
       }
    }
    $Q->free_result();
    return $data;
 }

 function createSubscriber(){
	$this->db->where('email', $_POST['email']);
	$this->db->from('subscribers');
	$ct = $this->db->count_all_results();

	if ($ct == 0){
		$data = array(
			'name' => $_POST['name'],
			'email' => $_POST['email']
		);

		$this->db->insert('subscribers', $data);
 	}
 }

 function updateSubscriber(){
	$data = array(
		'name' => $_POST['name'],
		'email' => $_POST['email']

	);

 	$this->db->where('id', $_POST['id']);
	$this->db->update('subscribers', $data);	

 }

 function removeSubscriber($id){
 	$this->db->where('id', $id);
	$this->db->delete('subscribers');

 } 

}//end class
?>

Controller

controllers/welcome.php

<?php
class Welcome extends Controller {
  function  __construct(){
    parent::Controller();
    $this->load->model('MSubscribers');
    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');
    session_start();
    $this->output->enable_profiler(FALSE);
  }

  function index(){

    	$captcha_result = '';
	$data['cap_img'] = $this -> _make_captcha();
	$this->load->view('subscribe', $data);
  }

  function subscribe(){
    /**
	 * form_validation
	 */
	$this->form_validation->set_rules('name', 'Name', 'required');
	$this->form_validation->set_rules('email', 'Email',  'required|valid_email');
	$this->form_validation->set_rules('captcha', 'Captcha', 'required');
	if ( $this -> _check_capthca() ) {
        if ($this->form_validation->run() == FALSE)
		{
		    $this->session->set_flashdata('subscribe_msg', 'All fields are required . Please try again!');
		    redirect('welcome/index');
		}
		else
		{
		    $this->MSubscribers->createSubscriber();
		    $this->session->set_flashdata('subscribe_msg', 'Thanks for subscribing!');
		    redirect('welcome/index','refresh');
		}
      }else {
        $this->session->set_flashdata('subscribe_msg', 'Enter captcha . Please try again!');
	redirect('welcome/index');
      }
  }
  /**
   * For captcha
   *
   */
   function _make_captcha()
  {
    $this -> load -> plugin( 'captcha' );
    $vals = array(
      'img_path' => './captcha/', // PATH for captcha ( *Must mkdir (htdocs)/captcha )
      'img_url' => 'captcha/', // URL for captcha img
      'img_width' => 200, // width
      'img_height' => 60, // height
      // 'font_path'     => '../system/fonts/2.ttf',
      'expiration' => 7200 ,
      );
    // Create captcha
    $cap = create_captcha( $vals );
    // Write to DB
    if ( $cap ) {
      $data = array(
        'captcha_id' => '',
        'captcha_time' => $cap['time'],
        'ip_address' => $this -> input -> ip_address(),
        'word' => $cap['word'] ,
        );
      $query = $this -> db -> insert_string( 'captcha', $data );
      $this -> db -> query( $query );
    }else {
      return "Umm captcha not work" ;
    }
    return $cap['image'] ;
  }

  function _check_capthca()
  {
    // Delete old data ( 2hours)
    $expiration = time()-7200 ;
    $sql = " DELETE FROM captcha WHERE captcha_time < ? ";
    $binds = array($expiration);
    $query = $this->db->query($sql, $binds);

    //checking input
    $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
    $binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
    $query = $this->db->query($sql, $binds);
    $row = $query->row();

  if ( $row -> count > 0 )
    {
      return true;
    }
    return false;

  }

  /**
   * End of captcha
   */
}//end controller class

?>

View

views/subscribe.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Using captcha with Codeigniter</title>
  <base href="<?=base_url();?>">
  </head>
<body>
<div id='main'>

<?php
if ($this->session->flashdata('subscribe_msg')){
	echo "<div class='message'>";
	echo $this->session->flashdata('subscribe_msg');
	echo "</div>";
}
?>
<?php echo form_open("welcome/subscribe"); ?>
<?php echo form_fieldset('Subscribe To Our Newsletter'); ?>
<h5>Name</h5>
<input type="text" name="name" id="name" value="<?php echo set_value('name'); ?>" size="40" />

<h5>Email</h5>
<input type="text" name="email" id="email" value="<?php echo set_value('email'); ?>" size="40" />

<h5>Are you human?</h5>
<?php echo "<p>$cap_img</p>" ;?>

<input type="text" name="captcha" value="" size="40" />

<div><input type="submit" value="Subscribe" /></div>
<?php echo form_fieldset_close(); ?>
<?php echo form_close(); ?>
</div>
</body>
</html>

newsletter1

1 comment to How to use Codeigniter captcha plug-in Part 2

  • riki

    sorry Mr I ask

    1. why not the way to form validation when there has been in setting required
    2. why each time the refresh can be entered on to database

    thanks before.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>