laravel 图片验证码类库mews/captcha

2018-02-25 03:03:35   php分享记录

 

首先使用composer安装类库

  1. composer require mews/captcha

注册provider

  1. 'providers' => [
  2. // ...
  3. Mews\Captcha\CaptchaServiceProvider::class,
  4. ]
  5. 'aliases' => [
  6. // ...
  7. 'Captcha' => 'Mews\Captcha\Facades\Captcha',
  8. ]
  1. 生存相应配置文件
  2. php artisan vendor:publish
  3. 可以自定义自己的验证码样式,具体代码,请参照官方文档
  4. Captcha.config 文件下
  5. 'login' => [
  6. 'length' => 4,
  7. 'width' => 80,
  8. 'height' => 30,
  9. 'quality' => 90,
  10. 'lines' => 6,
  11. 'bgImage' => false,
  12. 'bgColor' => '#ecf2f4',
  13. 'fontColors'=> ['#2c3e50', '#c0392b', '#16a085', '#c0392b', '#8e44ad', '#303f9f', '#f57c00', '#795548'],
  14. 'contrast' => -5,
  15. 'angle' => 15,
  16. ]

创建相关验证码路由

  1. //-----------------通用-验证码-------------------//
  2. Route::get('create_code',['uses' => 'VerifyController@create_code','as' => 'create_code']);
  3. Route::post('check_code',['uses' => 'VerifyController@check_code','as' => 'check_code']);

相应控制器

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Mews\Captcha\Facades\Captcha;
  5. class VerifyController extends Controller{
  6. public function create_code(){
  7. return Captcha::create('login');
  8. }
  9. /**用于验证验证码**/
  10. public function check_code(Request $request){
  11. $validator = Captcha::check($request->input('verify'));
  12. return response()->json($validator);
  13. }
  14. }

前台页面

  1. <div class="form-code-img pull-left">
  2. <img src="{{ route('create_code') }}" alt="" id="verify" name="login_code" onclick="this.src='{{ route('create_code') }}?r='+Math.random();" title="点击刷新">
  3. </div>