在Laravel中有很多图片验证码的库可以使用,本篇介绍其中之一:gregwar/captcha,这个库比较简单,在Laravel中比较常用。下面我们就来介绍下使用细节:
首先, composer.json中如下加入配置:
"require": {
...
"gregwar/captcha": "1.*"
},
然后,已成习惯的命令:用cmd执行下面这条命令
composer update
以下演示了其中一种使用方式,直接输出图片到网页。
我定义了一个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,可以访问看到这张图片了