前提要安装gd库
安装:在项目根目录下使用
composer require gregwar/captcha
配置:在composer.json文件require项添加
"require":{
"gregwar/captcha":"1.*"
},
执行:composer update
使用:引入命名空间
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
以下例子:
注意:应该把验证码路由放在中间件外面Route::get('/captcha/{tmp}');
//生成验证码方法
public function captcha($tmp)
{
$phrase = new PhraseBuilder;
//设置验证码位数
$code = $phrase->build(4);
//生成验证码图片的Builder对象,配置相应属性
$builder = new CaptchaBuilder($code, $phrase);
//设置背景颜色
$builder->setBackgroundColor(123, 203, 230);
$builder->setMaxAngle(25);
$builder->setMaxBehindLines(0);
$builder->setMaxFrontLines(0);
//可以设置图片宽高及字体
$builder->build($width = 90, $height = 35, $font = null);
// 获取验证码的内容
$phrase = $builder->getPhrase();
//把内容存入session
\Session::flash('code', $phrase);
//生成图片
header("Cache-Control: no-cache, must-revalidate");
header("Content-Type:image/jpeg");
$builder->output();
}
模板案例
<input name="captcha" type="text" placeholder="验证码">
<a onclick="javascript:re_captcha();">
<img src="{{ URL('/code/captcha/1') }}" id="captchaid">
点击图片更换验证码JS
<script type="text/javascript">
function re_captcha() {
$url = "{{ URL('/code/captcha') }}";
$url = $url + "/" + Math.random();
document.getElementById('captchaid').src = $url;
}
</script>
内容来源:吕倡个人博客