用户
 找回密码
 入住 CI 中国社区
搜索
查看: 2684|回复: 2
收起左侧

[Web] 看到很多说验证码的,我来分享下我的方法

[复制链接]
发表于 2017-10-26 23:20:56 | 显示全部楼层 |阅读模式
原先做验证码都是用第三方的,后来发现好像CI有验证码类,就研究了下,其实也很简单
首先建立一个公共类common(验证码多处使用,放到公共类里方便),建立验证码的方法,直接输入图片
PHP复制代码
lass Common extends CI_Controller {
 
        /**
         公共功能
         */

         
         /**验证码**/
        public function captcha()
        {
                $this->load->helper('captcha');
                $this->load->helper('url');
                $this->load->library('session');
                $vals = array(
    //'word'      => 'Random word',
    'img_path'  => './captcha/',//目录需要可写属性
    'img_url'   => base_url().'captcha/',
    'font_path' =>  '/xxx/font.ttf',//使用服务器绝对路径,建议使用外部字体,不然字体大小不能定义
    'img_width' => '95',//宽高根据自身项目调整
    'img_height'    => 40,
    'expiration'    => 60,//一般来说60秒够了
    'word_length'   => 4,
    'font_size' => 22,
    'img_id'    => 'Imageid',
    'pool'      => '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ',//我把1iol0OLI全部删除了,太反人类了
 
 
    'colors'    => array(
        'background' => array(255, 255, 255),
        'border' => array(255, 255, 255),
        'text' => array(0, 0, 0),
        'grid' => array(15, 136, 235)
    )
);
 
$cap = create_captcha($vals);//创建验证码
$word= $cap['word'];
$this->session->set_userdata('captcha', $word);//把字符存储到session里
 
$fileres = file_get_contents(base_url().'captcha/'.$cap['time'].'.jpg');//读取生成的图片
header('Content-type: image/jpeg'); //定义图片
echo $fileres;
 
 
        }
       
}
复制代码

前端直接访问地址
HTML复制代码
 
<div class="group-ipt verify">
                                        <input type="text" name="verify" id="verify" class="ipt" placeholder="输入验证码" required>
                                        <img src="<?php echo site_url('common/captcha');?>" class="imgcode">
                                </div>
 
 
复制代码

然后再写一段点击刷新的JS
JS复制代码
 
$('.imgcode').hover(function(){
                layer.tips("看不清?点击更换", '.verify', {
                        time: 6000,
                        tips: [2, "#3c3c3c"]
                })
        },function(){
                layer.closeAll('tips');
        }).click(function(){
                $(this).attr('src','<?php echo site_url('common/captcha');?>');
        });
       
 
 
复制代码




完美!
发表于 2017-10-28 16:48:49 | 显示全部楼层
先收藏了,应该以后会用到,多谢

本版积分规则