一、实例化生成验证码的类(该方法放到IndexController里面便于访问)
- /**
- *
- * 验证码生成
- */
- public function verify_c(){
- $Verify = new ThinkVerify();
- $Verify->fontSize = 18;
- $Verify->length = 4;
- $Verify->useNoise = false;
- $Verify->codeSet = '0123456789';
- $Verify->imageW = 130;
- $Verify->imageH = 50;
- //$Verify->expire = 600;
- $Verify->entry();
- }
二、前台需要生成验证码的图片src属性指向
- <p class="top15 captcha" id="captcha-container">
- <input name="verify" width="50%" height="50" class="captcha-text" placeholder="验证码" type="text">
- <img width="30%" class="left15" height="50" alt="验证码" src="{:U('Home/Index/verify_c',array())}" title="点击刷新">
- </p>
三、写完上面的后,页面初始化的验证码就可以出现了,下面要写的就是点击验证码图片后,刷新出新的验证码图片(通过jquery修改图片的src属性来完成,请求的处理函数一样,只是在请求后加一个随机数,区别上一张图片的请求
- // 验证码生成
- var captcha_img = $('#captcha-container').find('img')
- var verifyimg = captcha_img.attr("src");
- captcha_img.attr('title', '点击刷新');
- captcha_img.click(function(){
- if( verifyimg.indexOf('?')>0){
- $(this).attr("src", verifyimg+'&random='+Math.random());
- }else{
- $(this).attr("src", verifyimg.replace(/?.*$/,'')+'?'+Math.random());
- }
- });
四、校验验证码输入是否正确
a.在common目录下的function.php里加入全局函数
- /**
- * 验证码检查
- */
- function check_verify($code, $id = ""){
- $verify = new ThinkVerify();
- return $verify->check($code, $id);
- }
b.在表单提交的controller对应的处理方法里添加检查代码
- // 检查验证码
- $verify = I('param.verify','');
- if(!check_verify($verify)){
- $this->error("亲,验证码输错了哦!",$this->site_url,9);
- }