Laravel生成验证码

做网站就少不了验证码,不说废话,直接干。

  • 安装Captcha包
$ composer require mews/captcha

注:Windows中使用该扩展包还需要安装 GD2 扩展(在php.ini中取消php_gd2.dll前面的注释)。

  • 在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,
    ],
];
  • 使用实例
// app/Http/routes.php
Route::any('captcha-test', function()
{
    if (\Request::getMethod() == 'POST')
    {
        $rules = ['captcha' => 'required|captcha'];
        $validator = \Validator::make(\Request::all(), $rules);
        if ($validator->fails())
        {
            echo '

Incorrect!

'; } else { echo '

Matched :)

'; } } $form = '
'; $form .= ''; $form .= '

'; $form .= '

'; $form .= '

'; $form .= '
'; return $form; });
  • 点击切换验证码

你可能感兴趣的:(Laravel生成验证码)