Welcome Guest, Not a member yet? Register   Sign In
integrate form validation and captcha helper
#1

[eluser]Unknown[/eluser]
application/libraries/MY_Form_validation.php
Code:
<?php
class MY_Form_validation extends CI_Form_validation
{
function __construct()
{
  parent::__construct();
}

public function captcha()
{
  // First, delete old captchas
  $expiration = time()-7200; // Two hour limit
  $this->CI->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);

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

  if ($row->count == 0)
  {
   $this->set_message('captcha', lang('captcha_err'));
   return FALSE;
  }else{
   return TRUE;
  }
}

function get_captcha()
{
  $vals = array(
      'word'  => '',
      'img_path'  => 'static/captcha/',
      'img_url'  => base_url().'static/captcha/',
      'font_path'  => './path/to/fonts/texb.ttf',
      'img_width'  => '150',
      'img_height' => 30,
      'expiration' => 7200
  );

  $cap = create_captcha($vals);

  $data = array(
      'captcha_time' => $cap['time'],
      'ip_address' => $this->CI->input->ip_address(),
      'word'  => $cap['word']
  );

  $query = $this->CI->db->insert_string('captcha', $data);
  $this->CI->db->query($query);

  return $cap['image'];
}
}

in controller
Code:
class Welcome extends CI_Controller {
                $this->load->library('form_validation');
  $this->form_validation->set_rules('captcha', lang('captcha'), 'required|captcha');
  
  if($this->form_validation->run() == TRUE)
  {
   // validate ok
  }else{
                        // add image to data to pass in view
   $data['captcha'] = $this->form_validation->get_captcha();
  }
                $this->load->view('welcome_message', $data);
}
in view
Code:
&lt;?php echo $captcha?&gt;
#2

[eluser]B3geN14S[/eluser]
Hi, I'm facing a problem with captcha validation. I followed the example provided above. I managed to visualise captcha on pages and to set expiration..., but no matter what I write in the input field, script proceeds to validation, no matter if what I entered matches the image text or not.
I aslo got this error:

A PHP Error was encountered
Severity: Notice
Message: Undefined index: captcha
Filename: libraries/MY_Form_validation.php
Line Number: 17


The content of MY_Form_validation.php, I'll post below.

I'm sure it's a ridiculous problem... Any help is appreciated.
Here's my code:

regform.php

Code:
<label for="captcha">Antispam check<span >*</span></label>
&lt;?php echo $captcha; ?&gt;
&lt;input type="text" id="captcha" name="captcha" value="" maxlength="8" placeholder="Please enter the code" /&gt;

form.php (Controller)

Code:
class Form extends CI_Controller {

function index()
{
$this->output->nocache();
$this->load->library('session');
$this->load->library('encrypt');
$this->load->helper(array('form', 'url'));
$this->load->helper('captcha');

$this->load->library('form_validation');
$this->form_validation->set_rules('captcha', 'Antispam check', 'required|captcha_err|max_length[8]|xss_clean');

if ($this->form_validation->run() == FALSE)
{
$this->form_validation->captcha();
// add image to data to pass in view
$data['captcha'] = $this->form_validation->get_captcha();
$this->load->view('regform', $data);
}
else
{
$captcha = $this->input->post( 'captcha' );
// and so on
$this->load->view('formsuccess');
}
}
}

MY_Form_validation.php

Code:
class MY_Form_validation extends CI_Form_validation
{
function __construct()
{
  parent::__construct();
}

public function captcha()
{
  // First, delete old captchas
  $expiration = time()-300; //Five minutes limit
  $this->CI->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);

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

  if ($row->count == 0)
  {
   $this->set_message('captcha_err', The %s field must content a valid captcha code.');
   return FALSE;
  }else{
   return TRUE;
  }
}

function get_captcha()
{
  $vals = array(
      'word'  => '',
      'img_path'  => path-to-captcha/',
      'img_url'  => base_url().'path-to-captcha/',
      'font_path'  => 'path-to-font.ttf',
      'img_width'  => '150',
      'img_height' => 30,
      'expiration' => 300
  );

  $cap = create_captcha($vals);

  $data = array(
      'captcha_time' => $cap['time'],
      'ip_address' => $this->CI->input->ip_address(),
      'word'  => $cap['word']
  );

  $query = $this->CI->db->insert_string('captcha', $data);
  $this->CI->db->query($query);

  return $cap['image'];
}
}

Thanks in advance!
#3

[eluser]treenef[/eluser]
What I do is generate a random four digit number using the random library.

Then in the controller I set this in a session. When the form is submitted I check the session matches the input text.

Code:
$random = "2839";  <- store this in a session

$vals = array(
      'word'  => $random,
      'img_path'  => path-to-captcha/',
      'img_url'  => base_url().'path-to-captcha/',
      'font_path'  => 'path-to-font.ttf',
      'img_width'  => '150',
      'img_height' => 30,
      'expiration' => 300
  );
#4

[eluser]CroNiX[/eluser]
According to your error message, $_POST['captcha'] doesn't exist on this line:
Code:
$binds = array($_POST['captcha'], $this->CI->input->ip_address(), $expiration);

Are you sure the field is named "captcha" in your form?

It looks like you have 2 errors on this line as well:
Code:
$this->set_message('captcha_err', The %s field must content a valid captcha code.');

The error message name (first parameter) needs to be the same name as the form validation rule. So 'captha_err' should just be 'captcha'. You are also missing a single quote from the beginning of the 2nd parameter.
#5

[eluser]B3geN14S[/eluser]
Thanks for you comment CroNiX,

Missing single quote is a stupid mistake of mine. I think it is correct in the original code. I must have omitted it when pasting the code here. I'll try also with the first parameter corrected.

And Yes! I'm sure the text input field is named "captcha" as in this portion of code:

Code:
<label for="captcha">Antispam check<span >*</span></label>
&lt;?php echo $captcha; ?&gt;
&lt;input type="text" id="captcha" name="captcha" value="" maxlength="8" placeholder="Please enter the code" /&gt;

Otherwise, I suppose the problem must reside in the logic (the Controller).

Code:
if ($this->form_validation->run() == FALSE)
{
$this->form_validation->captcha();
// add image to data to pass in view
$data['captcha'] = $this->form_validation->get_captcha();
$this->load->view('regform', $data);
}

If I call
Code:
$this->form_validation->captcha();
all I get is the captcha database purged after expiration time but form still submits with wrong captcha symbols combination in the input field.

I'll report back tomorrow.
#6

[eluser]B3geN14S[/eluser]
[quote author="treenef" date="1403702768"]What I do is generate a random four digit number using the random library.

Then in the controller I set this in a session. When the form is submitted I check the session matches the input text.

Code:
$random = "2839";  <- store this in a session

$vals = array(
      'word'  => $random,
      'img_path'  => path-to-captcha/',
      'img_url'  => base_url().'path-to-captcha/',
      'font_path'  => 'path-to-font.ttf',
      'img_width'  => '150',
      'img_height' => 30,
      'expiration' => 300
  );
[/quote]

Thanks for the option you proposed, treenef!
Since this is my first project with CodeIgniter, could you provide some sample code to make it clearer to me?
#7

[eluser]treenef[/eluser]
I'll post an example tomorrow.
#8

[eluser]B3geN14S[/eluser]
UPDATE

Hi, guys!

Just an update to my problem. It seems that after correcting the parameters CroNiX suggested, I succeded to make everything work fine!

What I also did, was to remove the call to this in the controller:

Code:
$this->form_validation->captcha();

That was the reason to the Undefined index: captcha error.
I didn't have to call the this function again in the controller... Ooops!

Sorry for bothering you, guys, and once more, thank you very much for your help!

P.S. Now my boss won't torture me like hell Wink




Theme © iAndrew 2016 - Forum software by © MyBB