YII2中驗證碼的使用


驗證碼的使用是比較頻繁的。YII2中已經幫我們做好了封裝。

首先我們在控制器里創建一個actions方法,用於使用yii\captcha\CaptchaAction

<?php

namespace app\controllers;

use YII;
use yii\web\Controller;

class IndexController extends Controller
{
    public function actionIndex()
    {
        if (YII::$app->request->isPost) {
            //獲取post過來的驗證碼
            $verify = YII::$app->request->post('verify');

            //我們手動進行驗證,第二個參數表示是否區分大小寫
            if ($this->createAction('captcha')->validate($verify, false)) {
                echo '成功';
            } else {
                echo '失敗';
            }

        } else {
            return $this->renderPartial('index');
        }
    }

    //actions的作用主要是共用功能相同的方法
    //當用戶訪問index/captcha時,actions就會調用yii\captcha\CaptchaAction方法
    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => null,
                //背景顏色
                'backColor' => 0x000000,
                //最大顯示個數
                'maxLength' => 4,
                //最少顯示個數
                'minLength' => 4,
                //間距
                'padding' => 2,
                //高度
                'height' => 30,
                //寬度
                'width' => 85,
                //字體顏色
                'foreColor' => 0xffffff,
                //設置字符偏移量
                'offset' => 4,
            ],
        ];
    }
}

顯示頁面代碼如下:

<?php
use yii\helpers\Url;
use yii\helpers\Html;
?>
<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>分頁顯示</title>
</head>
<body>
    <form action="<?php echo Url::toRoute('index/index'); ?>" method="post">
        驗證碼:<input type="text" name="verify"><br>
        <img id="verifyImg" src="<?php echo Url::toRoute('index/captcha'); ?>"><br>
        <input type="submit" value="提交">
        <input name="_csrf" type="hidden" value="<?php echo \Yii::$app->request->csrfToken; ?>">
    </form>

    <?php echo Html::jsFile('@web/js/jquery-3.3.1.min.js'); ?>
    <script type="text/javascript">
        $(function () {
            //處理點擊刷新驗證碼
            $("#verifyImg").on("click", function () {
                $.get("<?php echo Url::toRoute('index/captcha') ?>?refresh", function (data) {
                    $("#verifyImg").attr("src", data["url"]);
                }, "json");
            });
        });
    </script>
</body>
</html>

演示結果如下:

上面控制器中驗證碼的驗證方式是我們手動的。我們也可以創建一個模型配置rules()來自動完成。

<?php

namespace app\models;

use yii\base\Model;

class VerifyForm extends Model
{

    //變量名為你表單中輸入驗證碼控件的name
    public $verify;

    public function rules()
    {
        return [
            ['verify', 'required', 'message' => '請填寫驗證碼'],
            //注意captchaAction的設置,指向你顯示驗證碼的action,這里我們的是index/captcha
            ['verify', 'captcha', 'captchaAction' => 'index/captcha', 'caseSensitive' => false, 'message' => '驗證碼錯誤'],
        ];
    }
}

控制器代碼修改如下:

<?php

namespace app\controllers;

use YII;
use app\models\VerifyForm;
use yii\web\Controller;

class IndexController extends Controller
{
    public function actionIndex()
    {
        if (YII::$app->request->isPost) {
            $verify = new VerifyForm();
            $verify->load(YII::$app->request->post(), '');

            //自動驗證
            if ($verify->validate()) {
                echo '成功';
            } else {
                var_dump($verify->errors);
            }

        } else {
            return $this->renderPartial('index');
        }
    }

    //actions的作用主要是共用功能相同的方法
    //當用戶訪問index/captcha時,actions就會調用yii\captcha\CaptchaAction方法
    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => null,
                //背景顏色
                'backColor' => 0x000000,
                //最大顯示個數
                'maxLength' => 4,
                //最少顯示個數
                'minLength' => 4,
                //間距
                'padding' => 2,
                //高度
                'height' => 30,
                //寬度
                'width' => 85,
                //字體顏色
                'foreColor' => 0xffffff,
                //設置字符偏移量
                'offset' => 4,
            ],
        ];
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM