在 yii2 的controller中添加验证码,而非在model中添加验证码。只要在该控制器中添加actions方法,如下:
class LoginController extends Controller
{
//******
public function actions()
{
return [
'captcha' => [ //这个就是前端页面的captchaAction。
'class' => 'yii\captcha\CaptchaAction',
'height' => 50,
'width' => 80,
'minLength' => 4,
'maxLength' => 4,
],
];
}
//*****
}
再到view页面添加验证码,就可以。记得要加use yii\captcha\Captcha;
在view页面。核心代码如下:
<div class="page-container">
<p><img src="/ace/images/logo.png" width="350" style="margin-left: -15px;"></p>
<form action="<?= Url::to(['login'])?>" method="post">
<input type="text" name="username" class="username" placeholder="用户名">
<input type="password" name="password" class="password" placeholder="密 码">
<input type="text" name="chechimage" class="username">
<?= Captcha::widget(['name' => 'captchaimg', 'captchaAction' => 'captcha', 'imageOptions' => ['id' => 'captchaimg', 'title' => '换一个', 'alt' => '换一个', 'style' => 'cursor:pointer;margin-left:25px;'], 'template' => '{image}']); ?>
<button type="submit">登 录</button>
<div class="error"><span>+</span></div>
</form>
</div>
在登录的controller里面添加验证:
public function actionLogin()
{
$chechimage = Yii::$app->request->post('chechimage); //这个chcekimage就是前端传过来的
// $code = $this->createAction('captcha')->getVerifyCode();//这样就可以获取到验证码了。
$result = $this->createAction('captcha')->validate($chechimage, false);
if (!$result) {
return $this->reload('验证码错误!');
}
//此后你就可以做用户名和密码的判断什么了
/*当然,在getVerifyCode和validate的时候,yii2都调用了$session->open();注意是否要关掉,我在做的时候,因为要用api,用了第三方passport返回的accessToken做sessionId,所以在验证完后,我调用了Yii::$app->session->close();*/
//Yii::$app->session->close(); //要是你用系统息的sessionId就没有必要关session了。
//******
}
好了,核心代码写完了,有什么
分类: web
标签:
搜索
标签
study
ab
amap
apache
apahe
awk
aws
bat
centos
CFS
chrome
cmd
cnpm
composer
consul
crontab
css
curl
cygwin
devops
di
docker
docker,docker-compose
ethereum
excel
fiddler
fluentd
framework
front-end
git
gitgui
github
glide
go
golang
gorm
grafana
gzip
ioc
item2
iterm2
javascript
jenkins
jsonp
kafka
laradock
laravel
larval
linux
liunux
log
mac
mac, wi-fi
macos
magento
mariaDB
minikube
mongoDB
msp
mysql
netbeans
nginx
nodejs
nohup
npm
nsq
oracle
php
php-fpm
php7
phpstorm
php扩展
Protobuf
python
redis
scp
server
shell
soap
socket
socket5
sql
sre
ssdb
ssh
ssl
study
sublime
swift
system
td-agent
uml
v2ray
vagrant
vagrnat
vim
vpn
vue
vue.js
webpack
webrtc
websocket
webtatic
windows
windows7
word
wps
xdebug
yarn
yii2
yum
zookeeper
世界国家
互联网
以太坊
分类
前端
小程序
打印机
排序算法
搞笑
权限
粤语
缓存
网络
虚拟机
视频
设计模式
项目管理
热门文章
友情链接