Laravel5.5 实现图片验证码的获取以及验证api接口

本人感受用的比较好的验证码包,拿出来分享一下,傻瓜式教程,大佬别喷。

用户登录注册,无论前台后台,为了安全性仍是须要加入手机短信或图形验证码的,这样安全性会好不少php

由于不一样的需求,咱们能够返回图片、网址、HTML,根据前端需求来返回相应的数据html

首先要引入图片验证码的composer包

github地址:github.com/mewebstudio…前端

安装captcha:

composer require mews/captcha 
复制代码

找到config/app.php下的providers,添加以下代码git

\Mews\Captcha\CaptchaServiceProvider::class,
复制代码

找到config/app.php下的aliases``,添加以下代码github

'Captcha' => Mews\Captcha\Facades\Captcha::class,
复制代码

引入配置文件,选择相应的包web

php artisan vendor:publish
复制代码

则生成config/captcha.php安全

配置文件中的代码:例如长宽,flat配置等,我的以为使用默认配置吧,也没什么问题。bash

Return URL

captcha_src();
Captcha::src();
复制代码

Return HTML

captcha_img();
Captcha::img();
复制代码

To use different configurations

captcha_img('flat');
 
Captcha::img('inverse');
复制代码

你们能够参考demo(demo为composer包自带的)

Route::any('captcha-test', function()
    {
        if (Request::getMethod() == 'POST')
        {
            $rules = ['captcha' => 'required|captcha'];
            $validator = Validator::make(Input::all(), $rules);
            if ($validator->fails())
            {
                echo '<p style="color: #ff0000;">Incorrect!</p>';
            }
            else
            {
                echo '<p style="color: #00ff30;">Matched :)</p>';
            }
        }
    
        $form = '<form method="post" action="captcha-test">';
        $form .= '<input type="hidden" name="_token" value="' . csrf_token() . '">';
        $form .= '<p>' . captcha_img() . '</p>';
        $form .= '<p><input type="text" name="captcha"></p>';
        $form .= '<p><button type="submit" name="check">Check</button></p>';
        $form .= '</form>';
        return $form;
    });
复制代码

本次项目用到的方法以下:

路由:get为获取图片验证码,post为验证验证码是否正确app

Route::get('/captcha', 'AllController@captcha');
Route::post('/captcha/validate', 'AllController@captchaValidate');
复制代码

控制器中的方法:获取图片验证码返回的是url,若是想返回img标签或者html,请看上面的方法composer

public function captcha()
{
    $captcha['url'] = captcha_src();
    return $this->responseData($captcha);
}
复制代码

前端把验证码传过来进行验证

public function captchaValidate(Request $request)
{
   $rules = ['captcha' => 'required|captcha'];
   $validator = \Validator::make($request->all(), $rules);
   if ($validator->fails()){
       return $this->responseFailed('验证失败');
   } else {
       return $this->responseSuccess('验证成功');
   }
}
复制代码

若是一直返回验证失败,则须要在app/Http/Kernel.php中的$middleware加入如下信息

\Illuminate\Session\Middleware\StartSession::class
复制代码

配上接口文档图片:

image

获取以下验证码 d6qfe

验证验证码是否正确

image

纯原创,全部做品都是经验所得,但愿能够得到你们的支持。

相关文章
相关标签/搜索