laravel的验证码

laravel 拥有composer这个包管理工具 使用相关依赖就变得容易的多 

使用验证码,首先php要开启gd库

 

这次我们使用扩展库是gregwar/captcha

1.在根目录coposer.json添加如下

"require": { 
        ... 
        "gregwar/captcha": "1.*" 
    }, 

2.使用composer 更新

1
composer update

3.调用库中的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
 
namespace App\Http\Controllers\Backend;
 
use Illuminate\Http\Request;
 
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use Session;
 
class BackController extends Controller
{
  /**
     * 验证码生成
     * @param  [type] $tmp [description]
     * @return [type]      [description]
     */
    public function captcha($tmp)
    {
        //生成验证码图片的Builder对象,配置相应属性
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();
        //把内容存入session
        Session::flash('milkcaptcha', $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    } 
}

4.注册路由

//生成验证码
Route::get('login/captcha/{tmp}', 'BackController@captcha');

5.view中使用

1
<img  src="{{ url('login/captcha/1') }}"  alt="验证码" title="刷新图片" width="100" height="40" id="captcha_img" border="0">

6.后台验证

$code = $request->input('code');
 
 
if(Session::get('milkcaptcha')!=$code) {
  return redirect('/')->with('message','验证码错误');
}

 

posted @ 2019-09-11 08:33  volition丶L  阅读(193)  评论(0编辑  收藏  举报