1、直接使用别人封装好的,composer下载一个
composer require gregwar/captcha
2、直接设置各种属性和输出图片
<?php
/**
* 后台用户管理
*/
namespace App\Modules\Admin\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
class AdminController extends Controller
{
public function login(){
return view('admin/admin/login');
}
public function getCode(){
$phrase = new \Gregwar\Captcha\PhraseBuilder();
// 设置验证码位数
$code = $phrase->build(4, '0123456789');
// 生成验证码图片的Builder对象,配置相应属性
$builder = new \Gregwar\Captcha\CaptchaBuilder($code, $phrase);
// 设置背景颜色25,25,112
$builder->setBackgroundColor(255, 255, 255);
// 设置倾斜角度
$builder->setMaxAngle(25);
// 设置验证码后面最大行数
$builder->setMaxBehindLines(10);
// 设置验证码前面最大行数
$builder->setMaxFrontLines(10);
// 设置验证码颜色
$builder->setTextColor(0, 100, 0);
// 可以设置图片宽高及字体
$builder->build($width = 150, $height = 48, $font = null);
// 获取验证码的内容
$phrase = $builder->getPhrase();
// 把内容存入session
session()->put('CAPTCHA_IMG', $phrase);
// 生成图片
header('Cache-Control: no-cache, must-revalidate');
header('Content-Type:image/jpeg');
$builder->output();
}
}
3.html
<div style="display: flex;justify-content: space-between;align-items: center;">
<input type="text" name="code" lay-verify="required" placeholder="验证码(数字)" class="layui-input" style="width: 50%;">
<img src="{{ url('admin/admin/getCode') }}" id="code" style="cursor: pointer;border: 1px solid rgb(220, 222, 224);" onclick="reloadcode()">
</div>
4.js
// 点击图片切换验证码
function reloadcode(){
var verify=document.getElementById('code');
verify.setAttribute('src','/admin/admin/getCode?'+Math.random());
}