phpcodeignitercaptcha

Codeigniter captcha


I ran into a small problem what i cant figure out.

I would liked to use the captcha helper without database but nothing seems to be working.

in the construct i created a variable which generates a random string

   public function __construct()
   {
      parent::__construct();
      $this->rand = random_string('numeric', 4);
   }

passed this variable to the captcha values like this:

 $vals = array(
     'word'   => $this->rand,
     'img_path'  => './captcha/',
     'img_url'   => base_url() . 'captcha/',
     'font_path'    => './system/fonts/texb.ttf',
     'img_width'    => '150',
     'img_height' => 30,
     'expiration' => 7200
     );

 $cap = create_captcha($vals);

and wanted to validate it with a callback function like this

   function captcha_check()
   {
      if($this->input->post('code') != $this->rand)
      {
         $this->form_validation->set_message('captcha_check', 'Wrong captcha code, hmm are you the Terminator?');
         return false;
      }
   }

And nothing works, the problem is, captcha code is show with the image, the problem is the validation, if i type in the correct numbers in my captcha field it always showing me the error, no mather what i type in, could please someone give me a hint?

html:

  <label for="code">Count please </label>
      <?php echo $rand; ?>
  <input type="text" id="code" name="code" class="span3" />

validation line:

$this->form_validation->set_rules('code', 'Captcha', 'required|callback_captcha_check');

Solution

  • Modify your callback function like this:

       function captcha_check()
       {
          if($this->input->post('code') != $this->rand)
          {
             $this->form_validation->set_message('captcha_check', 'Wrong captcha code, hmm are you the Terminator?');
             return false;
          }
          return true;
       }
    

    EDIT:

    You need to move this line $this->rand = random_string('numeric', 4); out of the constructor because on each load of the controller it generates a new string, resulting in different values on the captcha initial load and the captcha verification. Simply place it before the $vals initialization.