yii2 验证码文字或背景颜色, 随机刷新

时间: 2017-04-22  分类: Yii2  收藏
yii2的验证码使用方法这里就不再发了, 网上有很多教程, 本站内搜索"验证码"也可以很快找到,
yii2自带的验证码是白背景蓝文字, 在各种个性的网站有时候显得非常不搭调, 想个性一点,
想要达到的目的是,点击验证码刷新时,背景颜色和文字颜色随机变化,可以自定义颜色,实现如下:

控制器
使用方法跟各教程一样, 只是把参数换到了帮助类Helper中
    public function actions() {
        $Helper = new Helper();
        return [
            'captcha' => $Helper->captcha(),
        ];
    }
Helper帮助类
注意captcha()方法返回的为数组, 颜色值为16进制
    public function captcha() {
        return [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'backColor'=>$this->captcha_color(1), //背景颜色
                'foreColor'=>$this->captcha_color(2),  //字体颜色
        ];
    }

    //验证码颜色生成 $type 1:backColor背景色 2:foreColor文字颜色
    public function captcha_color($type=1) {
        if(!in_array($type, array(1,2))) $type=1;
        if($type==1) {
            $bg_color_arr=array('15595519','16316664');
            $bg=$bg_color_arr[array_rand($bg_color_arr)];
            return (int) '0x'.$bg;
        } else {
            $text_color_arr=array('12326852','2185586');
            $tc=$text_color_arr[array_rand($text_color_arr)];
            return (int) '0x'.$tc;
        }
    }
分享到:

评论

昵 称: