CI_中使用自定义的验证码

来源:互联网 发布:宏业软件公司地址 编辑:程序博客网 时间:2024/06/16 15:48

注意点:

 1.base_url()并不能调用views中的文件。

 2.后台接收session的时候必须先用session_start()开启会话。

步骤一:复制以下代码,并保存为check.php文件,存放于static目录中(这个是DIY的验证码文件)

<?php

header("Content-Type:image/png");
//include_once("../../include/common.php");
#shuffle the charactors
// ASCII转字符
function strtoascii($start,$range){
    $str='';
    for($i=$start;$i<=($start+$range);$i++){
        $str.=chr($i);
    }
    return $str;
}
//随机数
function randstr(){    
    $chars=strtoascii(65,25).strtoascii(48,9).strtoascii(97,25);
    $chars=trim($chars);
    $res = str_shuffle($chars);
    $str = substr($res,0,5);
    //return strtolower($str);    
    return $str;    
}
//画布
$width=100;$height=20;$paint = imagecreatetruecolor($width,$height);
//背景色source,RGB
$backgroundcolor=imagecolorallocate($paint,64,128,255);
//前景色source,RGB
$frontcolor=imagecolorallocate($paint,255,255,255);
//矩形
imagefilledrectangle($paint,0,0,$width,$height,$backgroundcolor);
//生成随机字符
 $get_code= randstr();
//写入随机字符
imagestring($paint,20,20,1,$get_code,$frontcolor);
//生成随机像素点
for($i=0;$i<=200;$i++){
        $x = mt_rand(0,$width);
        $y = mt_rand(0,$height);
        imagesetpixel($paint,$x,$y,imagecolorallocate($paint,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
      }
//会话开启-***必须开启,不然会失败****_
session_start();
//把随机字符存入会话
$_SESSION['bug']=$get_code;
imagepng($paint);   //在浏览器上面输出一张png图片

?>

步骤二:把下面代码复制到需要显示验证码的地方(也就是views里面的需要验证码的文件)

<img  src="<?php echo base_url('static/check.php');?>" onclick='_refresh(this);' />
<!--验证码刷新的js-->            
<script type="text/javascript">
    function _refresh(el){
        _value=el.getAttribute('src');
        el.setAttribute('src',_value+"?");    
    }
</script>

步骤三:在后台接受并验证session

    public function captcha(){
        session_start();//必须开启session,不然会报错
        //var_dump($_SESSION['bug']);exit;
            $yz = $this->input->post('yz')?$this->input->post('yz'):NULL;
        if($yz == $_SESSION['bug']){
            exit($yz);
            }
            else{
                exit("please input the captcha!!!");
            }
    }


0 0