1、安裝
我們通過 Composer 安裝Captcha 擴充包 :
composer require mews/captcha
註:Windows中使用該擴充包還需要安裝 GD2 擴充(在 php.ini 中取消 php_gd2.dll 前面的注釋)。
2、配置
使用Captcha服務提供者之前還需要在 config/app.php 中註冊服務提供者:
'providers' => [ // ... Mews\Captcha\CaptchaServiceProvider::class,]
同時註冊下相應門面:
'aliases' => [ // ... 'Captcha' => Mews\Captcha\Facades\Captcha::class,]
如果要使用自訂的配置,還發行就緒設定檔到 config 目錄:
$ php artisan vendor:publish
編輯新產生的 captcha.php :
return [ 'default' => [ 'length' => 5, 'width' => 120, 'height' => 36, 'quality' => 90, ], // ...];
3、使用樣本
// app/Http/routes.phpRoute::any('captcha-test', function(){ if (Request::getMethod() == 'POST') { $rules = ['captcha' => 'required|captcha']; $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { echo 'Incorrect!
'; } else { echo 'Matched :)
'; } } $form = ''; return $form;});
顯示效果如下:
如果要返回原生圖片,可以調用這個函數:
captcha();
或者
Captcha::create();
如果要返回URL:
captcha_src();
或者
Captcha::src();
如果要返回HTML:
captcha_img();
我們這個樣本中使用的就是這個函數,或者調用 Captcha 門面上的方法:
Captcha::img();
要使用設定檔 captcha.php 中不同的配置項,可以這樣調用:
captcha_img('flat');Captcha::img('inverse');