可能對於很多像我這樣yii的菜鳥級的同志,每次百度到的答案是一長段復雜的代碼,內心是崩潰的。所以下面就盡我可能簡單的實現驗證碼
1.現在你的控制器里寫上這些代碼
<?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'); } }
2.在頁面 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 就呈現這樣的效果
ok,就這樣完成了。