验证码
在models文件中的*****.Form.pnp
添加
use yii\captcha\Captcha;
public $verifyCode;
['verifyCode', 'required'],
['verifyCode', 'captcha','captchaAction'=>'backsite/captcha','message'=>'验证码不正确'],
注意:
captchaAction为你controlles中得文件名称,如果不填会默认到site文件中。
message:报错信息。
代码:
{
return [
// username and password are both required
[['username', 'password_hash','verifyCode'], 'required'],
['verifyCode', 'captcha','captchaAction'=>'backsite/captcha','message'=>'验证码不正确'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password_hash', 'validatePassword'],
];
}
public function attributeLabels()
{
return [
'username'=>'用户名',
'password_hash'=>'密码',
'verifyCode'=>'验证码',
];
}
controller
参数可以根据自己需求去调试
{
return [
// 'captcha' =>
// [
// 'class' => 'yii\captcha\CaptchaAction',
// 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
// ], //默认的写法
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'backColor' => 0x000000,//背景颜色
'maxLength' => 6, //最大显示个数
'minLength' => 5,//最少显示个数
'padding' => 5,//间距
'height' => 40,//高度
'width' => 130, //宽度
'foreColor' => 000000, //字体颜色
'offset' => 4, //设置字符偏移量 有效果
//'controller'=>'login', //拥有这个动作的controller
],
];
}
views
这个是我根据我的页面样式调整,需要的可以自己调试css
如果你用的是默认文件site,请忽略
如果不是
一定要注意’captchaAction’ =>'backsite/captcha’这个参数,如果不填写当前使用的controllers文件,验证码是显示不出来的
<?php echo $form->field($model,'verifyCode',['template'=>'<div class="form-group has-feedback">{input}'.Captcha::widget([
'model' =>$model,
'attribute' =>'verifyCode',//模型中也要申明
'captchaAction' =>'backsite/captcha',//指定操作
'template' =>'{image}',//image代表此处生成验证码图片
'imageOptions' =>[
//以下atrribute属性,可自己扩展
'title' =>'点击刷新',
'style' =>'margin-left:20px;'
],
]).'{error}</div>'])->textInput(['class'=>'form-group input-text size-L','placeholder'=>'验证码','style'=>'width:150px,padding-left:25px','id'=>'verifyCode']);?>
目前只能展示字母,展示数字的代码稍后更新
展示数字
在vendor/yiisoft/yii2/captcha中创建Captchanum.php 名字随意
namespace yii\captcha;
class Captchanum extends CaptchaAction
{
/**
* Generates a new verification code.
* @return string the generated verification code
*/
protected function generateVerifyCode()
{
if ($this->minLength > $this->maxLength) {
$this->maxLength = $this->minLength;
}
if ($this->minLength < 3) {
$this->minLength = 3;
}
if ($this->maxLength > 20) {
$this->maxLength = 20;
}
$length = mt_rand($this->minLength, $this->maxLength);
$letters = '123456789123456789123456789';
$vowels = 'aeiou'; 数字+字母
$vowels='123456789';数字 二选一
$code = '';
for ($i = 0; $i < $length; ++$i) {
if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
$code .= $vowels[mt_rand(0, 4)];
} else {
$code .= $letters[mt_rand(0, 20)];
}
}
return $code;
}
}
改成自己创建的文件名