本文目录导读:

在ThinkPHP项目中,验证码的字体和颜色通常通过配置参数来控制,以下是详细的设置方法:
基本配置
在ThinkPHP中,验证码的配置通常在config/captcha.php文件中:
return [
// 验证码字符集合
'codeSet' => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY',
// 验证码字体大小(px)
'fontSize' => 25,
// 是否画混淆曲线
'useCurve' => true,
// 验证码图片高度
'imageH' => 0,
// 验证码图片宽度
'imageW' => 0,
// 验证码位数
'length' => 4,
// 验证码字体,不设置随机获取
'fontttf' => '',
// 背景颜色
'bg' => [243, 251, 254],
// 验证码颜色
'color' => [0, 0, 0],
// 验证码过期时间(s)
'expire' => 1800,
// 是否使用中文验证码
'useZh' => false,
];
自定义字体设置
通过配置文件设置
// config/captcha.php
return [
'fontttf' => './static/fonts/your-font.ttf', // 指定字体文件路径
'fontSize' => 30,
'color' => [33, 33, 33], // RGB颜色值
];
动态设置
use think\captcha\facade\Captcha;
// 动态设置验证码参数
$config = [
'fontttf' => './static/fonts/arial.ttf',
'fontSize' => 28,
'color' => [255, 0, 0], // 红色
'bg' => [255, 255, 255], // 白色背景
'useCurve' => false,
];
// 生成验证码
return Captcha::create($config);
在控制器中使用
<?php
namespace app\controller;
use think\captcha\facade\Captcha;
class Verify
{
// 生成验证码
public function verify()
{
$config = [
'fontttf' => './public/static/fonts/simhei.ttf',
'fontSize' => 32,
'length' => 4,
'imageW' => 200,
'imageH' => 60,
'color' => [50, 20, 200], // 自定义颜色
'bg' => [245, 245, 245],
'useCurve' => true,
'useNoise' => true,
];
// 使用自定义配置生成验证码
return Captcha::create($config);
}
// 验证验证码
public function check()
{
$code = input('post.code');
if (Captcha::check($code)) {
return json(['code' => 1, 'msg' => '验证码正确']);
} else {
return json(['code' => 0, 'msg' => '验证码错误']);
}
}
}
字体文件说明
常用中文字体文件位置
public/static/fonts/
├── simhei.ttf // 黑体
├── simsun.ttf // 宋体
├── msyh.ttf // 微软雅黑
├── arial.ttf // Arial
└── custom-font.ttf // 自定义字体
使用系统自带字体
'fontttf' => '5', // 数字1-5表示系统内置字体
自定义颜色方案
// 随机颜色生成
$randomColor = [
rand(0, 255),
rand(0, 255),
rand(0, 255)
];
// 特定颜色方案
$config = [
'color' => [66, 133, 244], // Google蓝色
'bg' => [255, 255, 255], // 白色背景
'fontttf' => './public/static/fonts/custom.ttf',
'fontSize' => 28,
];
前端调用示例
<!-- HTML模板中 -->
<img src="{:captcha_src()}" alt="验证码" onclick="this.src=this.src+'?t='+Math.random()" />
<!-- 或者 -->
<img src="/verify/verify" alt="验证码" onclick="this.src='/verify/verify?t='+new Date().getTime()" />
注意事项
- 字体路径问题:确保字体文件路径正确,相对于项目根目录
- 字体兼容性:某些特殊字符可能需要特定的字体支持
- 性能考虑:使用系统字体比自定义字体加载更快
- 安全性:建议使用复杂一点的字体和颜色,增加验证码破解难度
如果需要修改默认配置,建议在config/captcha.php中进行统一的全局设置。