最近需要用到验证码,搜索了很多关于yii2验证码的切换的介绍,下面我来记录一下,有需要了解yii2下验证码的切换的朋友可参考。希望此文章对各位有所帮助。
模型代码如下:
<?php
namespace appadminmodels;
use yii;
use yiibasemodel;
use yiicaptchacaptcha;
class loginform extends model{
public $verifycode;
public $password;
public $username;
public function rules(){
return [
['verifycode','captcha','captchaaction'=>'/admin/login/captcha','message'=>'{attribute}'],
[['password','username'],'required'],
];
}
}
控制器代码如下:
<?php
namespace appadmincontrollers;
use yii;
use yiiwebcontroller;
use appadminmodelsloginform;
use yiifiltersaccesscontrol;
use yiifiltersverbfilter;
use yiicaptchacaptchaaction;
class logincontroller extends controller{
public function actions(){
return [
'captcha'=>'yiicaptchacaptchaaction',
'maxlength'=>4,
'minlength'=>3,
'width'=>10,
'height'=>10
];
}
public function actionindex(){
$log = new loginform();
return $this->renderpartial("index",['model'=>$log]);
}
//授权规则
}
视图代码如下:
<?php
use yiihelpershtml;
use yiibootstrapnav;
use yiibootstrapnavbar;
use yiiwidgetsbreadcrumbs;
use appassetsappasset;
use yiiwidgetsactivefiel;
use yiiwidgetsactiveform;
use yiicaptchacaptcha;
use appcomponentshellowidget;
//url 创建
use yiihelpersurl;
appasset::register($this);
?>
<?php $this->beginpage()?>
<!doctype html>
<html>
<head>
<title>博客后台管理系统</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1" />
<?=html::cssfile('@web/css/bootstrap.min.css')?>
<?=html::cssfile('@web/css/style.css')?>
<?=html::jsfile("@web/js/jquery-1.11.3.min.js");?>
<?=html::jsfile("@web/js/bootstrap.min.js");?>
<?php ?>
</head>
<?php $this->beginbody()?>
<body>
<div class="login-box">
<div class="login">
<div class="login-icon">
</div>
<h4 class="login-title">博客后台管理系统</h4>
<?php $form=activeform::begin(['method'=>'post','action'=> yii::$app->urlmanager->createurl('/admin/login/index')])?>
<div class="login-input-box mb10">
<input type="text" class="form-control" name="username" placeholder="用户名">
</div>
<div class="login-input-box mb10">
<input class="form-control" type="password" name="password" placeholder="密码">
</div>
<div class="login-input-box mb30">
<input class="form-control" type="text" name="code" placeholder="验证码">
<span class="login-code">
<img id="code_img" src="<?= url::toroute('/admin/login/captcha')?>" title="点击刷新验证码" onclick="get_code(this);">
</span>
</div>
<input class="inputbtn bg-success btn-block" type="submit" value="登 录">
<?php activeform::end();?>
</div>
</div>
<script type="text/javascript">
//刷新验证码
function get_code(obj)
{
if(!obj)
{
obj = document.getelementbyid('code_img');
}
obj.src = obj.src + "&t="+date.parse(new date());
}
</script>
</body>
<?php $this->beginbody()?>
</html>
<?php $this->endpage()?>
这里整个代码差不多了但是要设置一样更重要的 app/vendor/yiisoft/yii2/captcha/的文件下的captchaaction.php这文件中修改getverifycode($regenerate = false) 的方法$regenerate参数为true (getverifycode($regenerate = true))
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持硕编程。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!