主要解決方法:
1)繼承Yii2的yii\captcha\CaptchaAction,重寫run方法進行驗證碼的生成、顯示等操作。
2)改變getVerifyCode的參數false改為true,讓每次刷新和請求都更新驗證碼
3)讓驗證碼更美觀,用新的字體,加上線條,背景等
有其他特殊需求可以在這些代碼中自己添加即可。
控制器代碼SiteController.php:
public function actions()
{
return [
'captcha' => [
'class' => 'common\components\MyCaptcha',
//'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'maxLength' => 4, //生成的驗證碼最大長度
'minLength' => 4, //生成的驗證碼最短長度
'width'=>130,
'height'=>50,
],
];
}
驗證碼common/components/MyCaptcha.php:
<?php
namespace common\components;
use Yii;
use yii\captcha\CaptchaAction;
use yii\helpers\Url;
use yii\web\Response;
class MyCaptcha extends CaptchaAction
{
public function init()
{
parent::init();
$this->fontFile = dirname(Yii::$app->basePath) . '/source/font/elephant.ttf';
}
/**
* Runs the action.
*/
public function run()
{
if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
// AJAX request for regenerating code
$code = $this->getVerifyCode(true);
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'hash1' => $this->generateValidationHash($code),
'hash2' => $this->generateValidationHash(strtolower($code)),
// we add a random 'v' parameter so that FireFox can refresh the image
// when src attribute of image tag is changed
'url' => Url::to([$this->id, 'v' => uniqid()]),
];
} else {
$this->setHttpHeaders();
Yii::$app->response->format = Response::FORMAT_RAW;
return $this->renderImage($this->getVerifyCode(true));
}
}
/**
* Renders the CAPTCHA image based on the code using GD library.
* @param string $code the verification code
* @return string image contents in PNG format.
*/
protected function renderImageByGD($code)
{
$image = imagecreatetruecolor($this->width, $this->height);
$backColor = imagecolorallocate($image, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);
imagecolordeallocate($image, $backColor);
if ($this->transparent) {
imagecolortransparent($image, $backColor);
}
$foreColor = imagecolorallocate($image,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
//雪花線條
for ($i=0;$i<6;$i++) {
$color = imagecolorallocate($image,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imageline($image,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
for ($i=0;$i<100;$i++) {
$color = imagecolorallocate($image,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
imagestring($image,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color);
}
$length = strlen($code);
$box = imagettfbbox(30, 0, $this->fontFile, $code);
$w = $box[4] - $box[0] + $this->offset * ($length - 1);
$h = $box[1] - $box[5];
$scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
$x = 10;
$y = round($this->height * 27 / 40);
for ($i = 0; $i < $length; ++$i) {
$fontSize = (int) (rand(26, 32) * $scale * 0.8);
$angle = rand(-10, 10);
$letter = $code[$i];
$box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);
$x = $box[2] + $this->offset;
}
imagecolordeallocate($image, $foreColor);
ob_start();
imagepng($image);
imagedestroy($image);
return ob_get_clean();
}
}
視圖中的代碼:
<ul>
<li><i class="icon-user"></i><input type="text" id="user" placeholder="請輸入賬號" maxlength="20" autocomplete="false"><span></span></li>
<li><i class="icon-pwd"></i><input type="password" id="pwd" placeholder="請輸入密碼" maxlength="20" autocomplete="false"><span></span></li>
<li><i class="icon-ver"></i><input type="text" id="ver" placeholder="請輸入驗證碼" maxlength="4" autocomplete="false"><span></span>
<?php echo Captcha::widget(['name'=>'captchaimg','captchaAction'=>'site/captcha','imageOptions'=>['class'=>'captchaimg', 'title'=>'換一個', 'alt'=>'換一個'],'template'=>'{image}']);?></li>
<li><button id="login">登錄</button></li>
</ul>
<script type="text/javascript">
$(".captchaimg").click(function(){
var date = new Date();
$(this).attr('src',['site/captcha','data=',(new Date())].join('?'));
})
<script>
- Yii2使用Url組件
- Yii2的Html,Request組件詳解
- YII2.0框架, 多圖片上傳功能
- yii2-imagine配置
- 有潔癖的禁止默認YII自帶垃圾代碼(個人認為)、JS、CSS(新手教程)
- Yii2 API接口輸出統一Json和jsonp格式方法
- MySql 創建表的一些語句釋義
- Yii2聯合查詢(配合GridView)
- Yii 通用系統字典
- ArrayHelper的多維數組排序函數multisort,強大無比。
- 路由規則,在Url中替換使用'/'以外的符號連接
- 從excel文件中讀取表格內容,并批量寫入數據庫
- yii2注冊時驗證用戶名、郵箱等唯一性
- Yii2最全的實戰教程
- Composer安裝yii2-imagine 壓縮,剪切,旋轉,水印
- LinkPager增加總頁數 和總記錄數
- Yii2 獲取模塊名控制器名方法名
- Yii2使用yii2-adminlte+yii2-admin左側菜單子路徑不高亮問題又解
- 前端CSS框架
- Yii2 之 frontend 子模塊實踐之一:添加前后臺子模塊
- Yii2 之 frontend 子模塊實踐之二:構建子模塊的獨立配置
- Yii2 之 frontend 子模塊實踐之三:布局和語言配置
- 完美解決ajax驗證碼不刷新問題,讓驗證碼更加美觀,不修改任何源代碼
- yii2.0 表單小部件常用的默認選中
- Yii2 controller 傳值給layout
- yii2 dropDownList 二級和三級 聯動寫法
- 微信掃碼登錄 新窗口二維碼 掃完關閉二維碼頁面 進入登錄頁面
- yii2 實現 "上一篇,下一篇" 功能
- Yii 行為簡單應用
- SQL語句