控制器里写上这些代码
<?php namespace frontend\controllers; use yii\web\Controller; class IndexController extends Controller { public function actions() { return [ 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', //'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, 'backColor' => 0x000000,//背景颜色 'maxLength' => 6, //最大显示个数 'minLength' => 5,//最少显示个数 'padding' => 5,//间距 'height' => 40,//高度 'width' => 130, //宽度 'foreColor' => 0xffffff, //字体颜色 'offset' => 4, //设置字符偏移量 有效果 ], ]; } public function actionIndex() { return $this->render('index'); } }
在页面 index.php 里写入一下代码,注意:captchaAction'=>'index/captcha’是写对应的控制器
<?php use yii\captcha\Captcha;?> <?php echo Captcha::widget(['name'=>'captchaimg','captchaAction'=>'index/captcha', 'imageOptions'=>['id'=>'captchaimg', 'title'=>'换一个', 'alt'=>'换一个', 'style'=>'cursor:pointer;margin-left:25px;'],'template'=>'{image}']);
然后打开页面:index/index 就呈现这样的效果