這裏選擇使用 gregwar/captcha , github地址:https://github.com/Gregwar/Captcha
其它驗證碼:
https://github.com/mewebstudio/captcha
環境: laravel 6.11.0
第一步: 安裝插件
composer require gregwar/captcha
第二步: 導入類
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
第三步: 定義路由
Route::get('imgcode','IndexController@imgCode')->name('imgcode');
第四步: 定義生成驗證碼方法
/*
* 圖片驗證碼
*/
public function imgCode()
{
$phrase = new PhraseBuilder;
// 設置驗證碼位數
$code = $phrase->build(4);
// 生成驗證碼圖片的Builder對象,配置相應屬性
$builder = new CaptchaBuilder($code, $phrase);
// 設置背景顏色25,25,112
$builder->setBackgroundColor(34, 0, 45);
// 設置傾斜角度
$builder->setMaxAngle(25);
// 設置驗證碼後面最大行數
$builder->setMaxBehindLines(10);
// 設置驗證碼前面最大行數
$builder->setMaxFrontLines(10);
// 設置驗證碼顏色
$builder->setTextColor(230, 81, 175);
// 可以設置圖片寬高及字體
$builder->build($width = 150, $height = 40, $font = null);
// 獲取驗證碼的內容
$phrase = $builder->getPhrase();
// 把內容存入session
session()->put('CAPTCHA_IMG', $phrase);
// 生成圖片
header('Cache-Control: no-cache, must-revalidate');
header('Content-Type:image/jpeg');
$builder->output();
}
第五步: 前臺網頁代碼編寫
<style>
.changeimgcode{
color:blue;
cursor:pointer;
}
</style>
<img id="elimg" src="{{route('imgcode')}}" style="width:100px;height:38px" οnclick="this.setAttribute('src','/imgcode?random='+Math.random())">
<span class="changeimgcode" id="changeimgcode" οncοntextmenu="return false;" onselectstart="return false">看不清換一換</span>
<script>
$('#changeimgcode').click(function(){
$('#elimg').trigger('click');
})
</script>
第六步: 登錄加入驗證碼判斷
$captchaImg = session('CAPTCHA_IMG');
$imgcode = $request->get('imgcode','');
if(!$imgcode)
{
return $this->retError('缺少驗證碼');
}
if(!$captchaImg)
{
return $this->retError('驗證碼錯誤');
}
if(strtolower($captchaImg) != strtolower($imgcode))
{
return $this->retError('驗證碼錯誤');
}
// 能走到這, 放行
效果圖: