yii2.0验证码的两种实现方式
第一种方式:采用model
1. 模型:Code.php
<?php
namespace app\models;
use yii\base\Model;
class Code extends Model
{
public $code;//添加的验证码字段
public function rules()
{
return [
//captchaAction 是生成验证码的控制器
['code', 'captcha', 'captchaAction' => 'demo/captcha', 'message' => '验证码不正确'],
];
}
}
控制器:DemoController.php
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
class DemoController extends Controller
{
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'maxLength' => 4,
'minLength' => 4,
'width' => 80,
'height' => 40,
],
];
}
public function actionCode()
{
$model = new \app\models\Code();
if(Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
if($model->valodate) {//验证
echo '验证成功';
} else{
//失败
var_dump($model->getErrors());
}
}
return $this->render('code', ['model' => $model]);
}
}
HTML :code.php
<?php
use \yii\helpers\Html;
?>
<?= Html::beginForm('', 'post', ['class' => 'form']);?>
<?=\yii\captcha\Captcha::widget([
'model' =>$model, //Model
'attribute' => 'code', //验证码的字段
'captchaAction' => 'demo/captcha', //验证码的action 与 Model是对应的
'template' => '{input}{image}', //模板,可以自定义
'options' => ['id' => 'input'], //input的HTML属性配置
'imageOptions' => ['alt' => '点击刷新验证码'], //image的HTML属性配置
])?>
<?=Html:submitButton('提交', ['class' => 'submit'])?>
<?php ActiveForm::end(); ?>
验证码显示:
第二种方式: 不采用model
2. 控制器:
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
class DemoController extends Controller
{
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'maxLength' => 4,
'minLength' => 4,
'width' => 80,
'height' => 40,
],
];
}
public function actionCodeTwo(){
if(Yii::$app->request->isPost) {//验证验证码
$code = $_POST['code'];
//实例化一个验证码验证对象
$cpValidate = new yii\captcha\CaptchaValidator();
//配置action为当前的
$cpValidate->captchaAction = 'demo/captcha';
//创建一个验证码对象
$cpAction = $cpValidate->createCaptchaAction();
//读取验证码
$scode = $cpAction->getVerifyCode();
if($code == $scode) {
echo ‘正确’;
}else{
echo '错误';
}
return $this->render('code');
}
视图:
<?php
use \yii\helpers\Html;
?>
<?= Html::beginForm('', 'post', ['class' => 'form']);?>
<?=\yii\captcha\Captcha::widget([
'name' => 'code',
'captchaAction' => 'demo/captcha', //验证码的action 与 Model是对应的
'template' => '{input}{image}', //模板,可以自定义
'options' => ['id' => 'input'], //input的HTML属性配置
'imageOptions' => ['alt' => '点击刷新验证码'], //image的HTML属性配置
])?>
<?=Html:submitButton('提交', ['class' => 'submit'])?>
<?php ActiveForm::end(); ?>
验证码显示:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧