使用 Captcha 扩展包 为 Laravel 5 应用生成验证码

WBOY
Release: 2016-06-23 13:07:48
Original
938 people have browsed it

1、安装

我们通过 Composer 安装Captcha 扩展包 :

composer require mews/captcha
Copy after login

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

2、配置

使用Captcha服务提供者之前还需要在 config/app.php 中注册服务提供者:

'providers' => [    // ...    Mews\Captcha\CaptchaServiceProvider::class,]
Copy after login

同时注册下相应门面:

'aliases' => [    // ...    'Captcha' => Mews\Captcha\Facades\Captcha::class,]
Copy after login

如果要使用自定义的配置,还可以发布配置文件到 config 目录:

$ php artisan vendor:publish
Copy after login

编辑新生成的 captcha.php :

return [    'default' => [        'length' => 5,        'width' => 120,        'height' => 36,        'quality' => 90,    ],    // ...];
Copy after login

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 '<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;});
Copy after login

显示效果如下:

如果要返回原生图片,可以调用这个函数:

captcha();
Copy after login

或者

Captcha::create();
Copy after login

如果要返回URL:

captcha_src();
Copy after login

或者

Captcha::src();
Copy after login

如果要返回HTML:

captcha_img();
Copy after login

我们这个示例中使用的就是这个函数,或者调用 Captcha 门面上的方法:

Captcha::img();
Copy after login

要使用配置文件 captcha.php 中不同的配置项,可以这样调用:

captcha_img('flat');Captcha::img('inverse');
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!