說明
mews/captcha 是一個非常易於集成的圖片驗證碼擴展包,使用此擴展包可以分分鐘給你的網站加上驗證碼功能。
完整的高質量擴展包推薦列表,請前往:下載量最高 100 個 Laravel 擴展包推薦
1. 安裝
1). 使用 composer 安裝:
composer require mews/captcha
2). 修改 config/app
文件,添加 ServiceProvider:
在 providers
數組內追加如下內容
'providers' => [
...
Mews\Captcha\CaptchaServiceProvider::class,
],
在 aliases
數組內追加如下內容
'aliases' => [
...
'Captcha' => Mews\Captcha\Facades\Captcha::class,
],
3). 運行 php artisan vendor:publish
生成配置文件 config/captcha.php
我們可以打開配置文件,查看其內容:
return [
'characters' => '2346789abcdefghjmnpqrtuxyzABCDEFGHJMNPQRTUXYZ',
'default' => [
'length' => 5,
'width' => 120,
'height' => 36,
'quality' => 90,
],
'flat' => [
'length' => 6,
'width' => 160,
'height' => 46,
'quality' => 90,
'lines' => 6,
'bgImage' => false,
'bgColor' => '#ecf2f4',
'fontColors'=> ['#2c3e50', '#c0392b', '#16a085', '#c0392b', '#8e44ad', '#303f9f', '#f57c00', '#795548'],
'contrast' => -5,
],
'mini' => [
'length' => 3,
'width' => 60,
'height' => 32,
],
'inverse' => [
'length' => 5,
'width' => 120,
'height' => 36,
'quality' => 90,
'sensitive' => true,
'angle' => 12,
'sharpen' => 10,
'blur' => 2,
'invert' => true,
'contrast' => -5,
]
];
可以看到這些配置選項都非常通俗易懂,你可以在此修改對應選項自定義驗證碼的長度、背景顏色、文字顏色等屬性,在此不做過多敘述。
至此,此擴展包就安裝完成了。
2. 用例
此擴展包的使用邏輯分爲兩步:
- 給用戶展示驗證碼;
- 驗證用戶輸入的驗證碼是否正確。
下面將分別爲大家講解。
2.1 給用戶展示驗證碼
擴展包提供了兩個函數用於展示驗證碼:
- captcha_img() - 返回 img 格式的驗證碼;
- captcha_src() - 返回驗證碼的 url 地址。
在你的模板文件裏(如:register.blade.php)直接調用即可:
<div class="form-group code">
<label>驗證碼</label>
<input class="tt-text" name="captcha">
{!! captcha_img() !!}
</div>
又或者:
<div class="form-group code">
<label>驗證碼</label>
<input class="tt-text" name="captcha">
<img src="{{captcha_src()}}">
</div>
輸出的效果如下:
使用自定義樣式的驗證碼
如果想使用自定義的驗證碼,如上文配置文件裏的 inverse
選項:
return [
...
'default' => [
...
],
'inverse' => [
'length' => 5,
'width' => 120,
'height' => 36,
'quality' => 90,
'sensitive' => true,
'angle' => 12,
'sharpen' => 10,
'blur' => 2,
'invert' => true,
'contrast' => -5,
]
];
則只要這樣調用即可:
{!! captcha_img('inverse') !!}
{{captcha_src('inverse')}}
展示的效果爲:
怎麼樣,是不是很簡單呢?
2.2 判斷用戶輸入的驗證碼是否正確
擴展包使用了 自定義驗證規則 方式擴展了驗證規則,我們只要在對應的 Controller 添加以下的規則即可:
$this->validate($request, [
'captcha' => 'required|captcha'
]);
同理,你也可以建立專門的 表單驗證 來處理此判斷。
以上。
本項目由 The EST Group 成員 @monkey 整理髮布,首發地爲 PHPHub 社區,轉載必須貼上原文鏈接 https://laravel-china.org/topics/2895