欢迎各位兄弟 发布技术文章

这里的技术是共享的

laravel5验证码 有大用

laravel5验证码

 

首先呢在laravel5中默认是没有提供验证码的,这里我们需要使用第三方提供的库:gregwar/captcha

通过composer安装:

在composer.json的require中加入"gregwar/captcha": "dev-master",具体代码如下

"require": {
        "laravel/framework": "5.0.*",
        "gregwar/captcha": "dev-master"
    },

然后运行:php composer.phar update命令

去github下载:

下载后将包放至vendor下目录结构如下

之后在composer.json文件中加入自动加载:

复制代码
"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "WangDong\\": "app/",
            "Gregwar\\Captcha\\": "vendor/Captcha/"
        }
    },
复制代码

然后运行composer的dump-autoload命令

使用gregwar/captcha

使用就非常简单了,直接上代码

$builder = new CaptchaBuilder;
$builder->build(150,32);
\Session::set('phrase',$builder->getPhrase()); //存储验证码
return response($builder->output())->header('Content-type','image/jpeg');

来自 http://www.cnblogs.com/xiaodo0/p/4401600.html

Laravel的验证码库gregwar/captcha

字数871 阅读5233 评论12 

原创作品,允许转载,转载时请务必以超链接形式标明原始出处、作者信息和本声明,否则后果自负。
如果你觉得这篇文章对你有帮助或启发,可直接留言和我沟通**


案例展示

在Laravel中有很多图片验证码的库可以使用,本篇介绍其中之一:gregwar/captcha,这个库比较简单,在Laravel中比较常用。下面我们就来介绍下使用细节:


首先, composer.json中如下加入配置:

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

然后,已成习惯的命令:

composer update

接下来就可以正常使用了,根据具体的开发需求,可以有很多种方式去使用。

  • 可以将验证码图片保存文件:
<?php

$builder->save('out.jpg');
  • 可以直接输出图片到网页:
<?php

header('Content-type: image/jpeg');
$builder->output();
  • 可以生成内联图片:
<img src="<?php echo $builder->inline(); ?>" />

以下演示了其中一种使用方式,直接输出图片到网页。

我定义了一个Controller:

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

//引用对应的命名空间
use Gregwar\Captcha\CaptchaBuilder;
use Session;

class KitController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    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();
    }

}

下面我们可以设置相应的router访问这个验证码图片, 修改router.php:

Route::get('kit/captcha/{tmp}', 'KitController@captcha');

现在可以通过具体的url,可以访问看到这张图片了


验证码

表单内部写的比较简单,看看即可:

<input type="text" name="captcha" class="form-control" style="width: 300px;">
          <a onclick="javascript:re_captcha();" ><img src="{{ URL('kit/captcha/1') }}"  alt="验证码" title="刷新图片" width="100" height="40" id="c2c98f0de5a04167a9e427d883690ff6" border="0"></a>

<script>  
  function re_captcha() {
    $url = "{{ URL('kit/captcha') }}";
        $url = $url + "/" + Math.random();
        document.getElementById('c2c98f0de5a04167a9e427d883690ff6').src=$url;
  }
</script>

最后就是在form提交页面验证相应验证码,库中也为我们提供了相应方法:

$userInput = $request->get('captcha');

if($builder->testPhrase($userInput)) {
    //用户输入验证码正确
    return '您输入验证码正确';
} else {
    //用户输入验证码错误
    return '您输入验证码错误';
}

至此,验证码就完成了。 如有疑问,欢迎回复探讨。

补充

在form表单提交验证的代码写的比较草率,给读者带来了歧义,在此有个补充(感谢 一块黄布 的回复):
$builder->testPhrase($userInput) 这里的$builder与生成验证码的$builder为同一个,如果重新new,则一直会验证失败。我们可以从源码中看到:

public function testPhrase($phrase)

 {

 return ($this->builder->niceize($phrase) == $this->builder->niceize($this->getPhrase()));

 }

验证码正确性判断,也可以由下列方式来验证:

$userInput = \Request::get('captcha');

if (Session::get('milkcaptcha') == $userInput) {
    //用户输入验证码正确
    return '您输入验证码正确';
} else {
    //用户输入验证码错误
    return '您输入验证码错误';
}

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

¥ 打赏支持 
 

应该把验证这写清楚一点
if($builder->testPhrase($userInput)) {
//用户输入验证码正确
}
else {
//用户输入验证码错误
}
就这里 

奶瓶: @一块黄布 感谢你的意见,我已经加了相应的补充,欢迎反馈建议与意见。

 

这个库生成验证码慢的一逼。本地测试都要800+ms

文/奶瓶(简书作者)
原文链接:http://www.jianshu.com/p/8e4ac7852b5a
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

header("Cache-Control: no-cache, must-revalidate");
header('Content-Type: image/jpeg');
$builder->output();
为什么按照这个方法总是出现乱码,查看源代码然后出现图片这是什么原因啊

CheungZee: @wang_wxd 
框架自带有一些输出。 在后面补一句 exit(0);就可以了。

Mr郭: @CheungZee 你好,如果后面补上了exit(0)的话,那么在Session::get的时候是取不到值的,并且这个session::flash也没有生成session数据

 
还有 1 条评论, 展开查看 添加新回复

楼主我特意注册账号来反对你。
在laravel中像你这样做,会造成很多中间件或服务失效。
控制器中只应该抛出异常或返回Resource。
绝对不能使用die()或者exit()
在现在,甚至ThinkPHP这种国产框架中都不建议在控制器中使用die了。

奶瓶: @shellus 首先你特地注册账号来提出建议我表示非常感谢并支持,函数die()和exit()目前一般用于程序的调试,而laravel也提供了些可用的内置函数帮助调试,如dd(),你的观点我也是支持的,不过我文章中并没有提到需要使用exit(),也没有相应代码。 :blush:

 

为什么失败啊

来自 http://www.jianshu.com/p/8e4ac7852b5a


Symfony2 bundle implementing a "captcha" form type
PHPHTML
 
Upload filesFind file
New pull request
Latest commit e1ed228 4 days ago@Gregwar  Merge pull request #168 from linnaea/patch-1 

 README.md

Gregwar's CaptchaBundle

The GregwarCaptchaBundle adds support for a captcha form type for the Symfony form component.

Compatibility with Symfony

If you are using Symfony < 2.8, you should use version 1.*

If you are using SYmfony >= 2.8, you should use version 2.*

Installation

Step 1: Download the GregwarCaptchaBundle

Ultimately, the GregwarCaptchaBundle files should be downloaded to the 'vendor/bundles/Gregwar/CaptchaBundle' directory.

You can accomplish this several ways, depending on your personal preference. The first method is the standard Symfony method.

Using Composer

Use composer require to download and install the package.

    composer require gregwar/captcha-bundle

Using the vendors script

Add the following lines to your deps file:

    [GregwarCaptchaBundle]
        git=http://github.com/Gregwar/CaptchaBundle.git
        target=/bundles/Gregwar/CaptchaBundle
        version=origin/2.0 <- add this if you are using Symfony 2.0

Now, run the vendors script to download the bundle:

$ php bin/vendors install

Using submodules

If you prefer instead to use git submodules, then run the following:

$ git submodule add git://github.com/Gregwar/CaptchaBundle.git vendor/bundles/Gregwar/CaptchaBundle
$ git submodule update --init

Step 2: Configure the Autoloader

If you use composer, you can skip this step.

Now you will need to add the Gregwar namespace to your autoloader:

<?php
// app/autoload.php

$loader->registerNamespaces(array(
    // ...
    'Gregwar' => __DIR__.'/../vendor/bundles',
));

Step 3: Enable the bundle

Finally, enable the bundle in the kernel:

<?php
// app/appKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Gregwar\CaptchaBundle\GregwarCaptchaBundle(),
    );
}

Configuration

Add the following configuration to your app/config/config.yml:

gregwar_captcha: ~

Usage

You can use the "captcha" type in your forms this way:

<?php
    use Gregwar\CaptchaBundle\Type\CaptchaType;
    // ...
    $builder->add('captcha', CaptchaType::class); // That's all !
    // If you're using php<5.5, you can use instead:
    $builder->add('captcha', 'Gregwar\CaptchaBundle\Type\CaptchaType');
    // ...

Note that the generated image will, by default, be embedded in the HTML document to avoid dealing with route and subrequests.

Options

You can define the following configuration options globally:

  • image_folder: name of folder for captcha images relative to public web folder in case as_file is set to true (default="captcha")
  • web_path: absolute path to public web folder (default="%kernel.root_dir%/../web")
  • gc_freq: frequency of garbage collection in fractions of 1 (default=100)
  • expiration: maximum lifetime of captcha image files in minutes (default=60)

You can define the following configuration options globally or on the CaptchaType itself:

  • width: the width of the captcha image (default=120)
  • height: the height of the captcha image (default=40)
  • disabled: disable globally the CAPTCHAs (can be useful in dev environment), it will still appear but won't be editable and won't be checked
  • length: the length of the captcha (number of chars, default 5)
  • quality: jpeg quality of captchas (default=30)
  • charset: the charset used for code generation (default=abcdefhjkmnprstuvwxyz23456789)
  • font: the font to use (default is random among some pre-provided fonts), this should be an absolute path
  • keep_value: the value will be the same until the form is posted, even if the page is refreshed (default=true)
  • as_file: if set to true an image file will be created instead of embedding to please IE6/7 (default=false)
  • as_url: if set to true, a URL will be used in the image tag and will handle captcha generation. This can be used in a multiple-server environment and support IE6/7 (default=false)
  • invalid_message: error message displayed when an non-matching code is submitted (default="Bad code value", see the translation section for more information)
  • bypass_code: code that will always validate the captcha (default=null)
  • whitelist_key: the session key to use for keep the session keys that can be used for captcha storage, when using as_url (default=captcha_whitelist_key)
  • reload: adds a link to reload the code
  • humanity: number of extra forms that the user can submit after a correct validation, if set to a value different of 0, only 1 over (1+humanity) forms will contain a CAPTCHA (default=0, i.e each form will contain the CAPTCHA)
  • distortion: enable or disable the distortion on the image (default=true, enabled)
  • max_front_linesmax_behind_lines: the maximum number of lines to draw on top/behind the image. 0 will draw no lines; null will use the default algorithm (the number of lines depends on the size of the image). (default=null)
  • background_color: sets the background color, if you want to force it, this should be an array of r,g &b, for instance [255, 255, 255] will force the background to be white
  • background_images: Sets custom user defined images as the captcha background (1 image is selected randomly). It is recommended to turn off all the effects on the image (ignore_all_effects). The full paths to the images must be passed.
  • interpolation: enable or disable the interpolation on the captcha
  • ignore_all_effects: Recommended to use when setting background images, will disable all image effects.

Example :

<?php
    use Gregwar\CaptchaBundle\Type\CaptchaType;
    // ...
    $builder->add('captcha', CaptchaType::class, array(
        'width' => 200,
        'height' => 50,
        'length' => 6,
    ));

You can also set these options for your whole application using the gregwar_captcha configuration entry in your config.ymlfile:

gregwar_captcha:
    width: 200
    height: 50
    length: 6

Translation

The messages are using the translator, you can either change the invalid_message option or translate it. Any contribution about the language is welcome !

As URL

To use a URL to generate a captcha image, you must add the bundle's routing configuration to your app/routing.yml file:

gregwar_captcha_routing:
    resource: "@GregwarCaptchaBundle/Resources/config/routing/routing.yml"

This will use the bundle's route of "/generate-captcha/{key}" to handle the generation. If this route conflicts with an application route, you can prefix the bundle's routes when you import:

gregwar_captcha_routing:
    resource: "@GregwarCaptchaBundle/Resources/config/routing/routing.yml"
    prefix: /_gcb

Since the session key is transported in the URL, it's also added in another session array, under the whitelist_key key, for security reasons

Form Theming

The widget support the standard Symfony theming, see the documentation for details on how to accomplish this.

The default rendering is:

{% block captcha_widget %}
{% spaceless %}
    <img src="{{ captcha_code }}" title="captcha" width="{{ captcha_width }}" height="{{ captcha_height }}" />
    {{ form_widget(form) }}
{% endspaceless %}
{% endblock %}

Image creation

If you choose to use image files instead of embedding the widget will execute a garbage collection randomly and delete images that exceed the configured lifetime.

License

This bundle is under the MIT license. See the complete license in the bundle: LICENSE

来自  https://github.com/Gregwar/CaptchaBundle

可以继承一个类来实现设置字体大小的功能

设置字体大小


唯物品评历史

关注"唯物品评历史",跟着泪痕春雨先生,读懂历史,看彻人生

打开隐藏二维码