我正在尝试在codeigniter中为我的登录表单添加验证码。
验证码显示正常。问题在于验证它。 当调用validate_captcha时,输入post的值是正确的,但会话值是新的页面值。(例如,如果在第1页上加载验证码是12345(让我们假设在第二次加载时它将是54321)。然后在第一次加载时用户输入12345将使用54321进行检查。
我该怎么办?
这是我试过的
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function index()
{
$capCode = rand(10000, 99999);
$this->session->set_userdata(array('captcha'=>$capCode));
echo $this->session->userdata['captcha'];//for debug only
$this->load->helper('captcha');
$vals = array(
'word' => $capCode ,
'img_path' => CAPTCHA_PATH,
'img_url' => base_url().CAPTCHA_PATH,
'img_width' => '150',
'img_height' => 30,
'expiration' => 1200
);
$cap = create_captcha($vals);
$data = array('un' => $un,'defTab'=>'','captcha'=>$cap);
$this->load->library('form_validation');
//I need to load different data if form is result of a post($data['defTab'])
if($this->input->post('submit'))
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('captcha', 'Captcha', 'required|callback_validate_captcha');
if ($this->form_validation->run() == FALSE)
{
$data['defTab'] = 'what i need';
$this->load->view('login',$data);
}
else
{
print_r($this->input->post());
}
}
else
{
$this->load->view('login',$data);
}
}
public function validate_captcha()
{
$sss=$this->input->post('captcha');
//I Use this line to find problem
$this->form_validation->set_message('validate_captcha', 'session:'.$this->session->userdata['captcha'].'\nPosted val:'.$sss);
if($sss!= $this->session->userdata['captcha'])
{
return false;
}
else
{
return true;
}
}
}
答案 0 :(得分:0)
您必须在创建表单期间设置会话:
.
.
.
} else {
if (isset($cap["word"])) {
$this->session->set_userdata("word", $cap["word"]);
}
$this->load->view('login',$data);
}
在验证过程中,请检查:
if($this->input->post("word", TRUE) == $this->session->userdata("word")){
// do something
}
答案 1 :(得分:0)
在调用create_captcha方法之前,请使用以下代码设置以前的验证码
$this->session->set_userdata('prev_captcha',$this->session->userdata('captcha_word'));
如果captcha_word包含当前的验证码 并检查如下
function checkCaptcha($str){
$word = $this->session->get('prev_captcha');
if(strcmp(strtoupper($str),strtoupper($word)) == 0){
return true;
}else{
return false;
}
}