豌豆Ai站群搜索引擎系统 V.25.10.25 网址:www.wd.chat

🗣 Wd提问: php生成验证码

🤖 Ai回答:
以下是使用 PHP 生成验证码的完整示例代码,包含图片生成、干扰元素和 Session 存储验证码:

php
<?php
session_start();
header('Content-Type: image/png');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// 配置参数
$width = 120;
$height = 40;
$characters = 4;
$fontSize = 20;
$fontFile = 'arial.ttf'; // 确保字体文件存在或替换为你的字体路径

// 创建画布
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);

// 添加干扰线
for ($i = 0; $i < 6; $i++) {
$color = imagecolorallocate($image, mt_rand(100, 200), mt_rand(100, 200), mt_rand(100, 200));
imageline(
$image,
mt_rand(0, $width),
mt_rand(0, $height),
mt_rand(0, $width),
mt_rand(0, $height),
$color
);
}

// 添加干扰点
for ($i = 0; $i < 100; $i++) {
$color = imagecolorallocate($image, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
imagesetpixel($image, mt_rand(0, $width), mt_rand(0, $height), $color);
}

// 生成随机验证码
$allowedChars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'; // 排除易混淆字符
$code = '';
for ($i = 0; $i < $characters; $i++) {
$code .= $allowedChars[mt_rand(0, strlen($allowedChars) 1)];
}
$_SESSION['captcha'] = $code;

// 绘制验证码文本
$textColor = imagecolorallocate($image, mt_rand(0, 80), mt_rand(0, 80), mt_rand(0, 80));
$x = ($width strlen($code) * $fontSize) / 2;
$y = $height ($height $fontSize)/2;
imagettftext($image, $fontSize, 0, $x, $y, $textColor, $fontFile, $code);

// 输出并销毁资源
imagepng($image);
imagedestroy($image);
?

使用说明:

1、创建验证码图片
在页面中通过 `<img` 标签引用:
html
<img src=captcha.php alt=验证码 style=width:120px;height:40px;


2、验证验证码
在表单提交时检查用户输入:
php
if ($_POST['user_input'] == $_SESSION['captcha']) {
echo 验证通过!;
} else {
echo 验证码错误!;
}


关键特性:

1、安全优化
排除易混淆字符(如 0/O, 1/I, l/L)
使用 `mt_rand()` 替代 `rand()` 生成更安全的随机数
设置 HTTP 头防止缓存

2、干扰元素
随机干扰线和干扰点
随机背景色和字体颜色

3、可定制性
可调整验证码长度($characters)
可修改字体文件路径($fontFile)
可调整图片尺寸($width, $height)

注意事项:

1、确保服务器已启用 GD 库
2、字体文件路径需要正确(如果使用 TrueType 字体)
3、请将验证码存储在 Session 中并设置有效期
4、建议添加噪点时控制数量以免影响可读性

扩展功能建议:

1、添加验证码有效期(在 Session 中记录生成时间)
2、实现验证码倒计时刷新功能
3、添加图片扭曲效果
4、支持动态调整验证码难度

如果需要更简单的版本(不使用 TrueType 字体),可以将字体相关代码替换为:

php
// 替换 imagettftext 部分为:
imagestring($image, 5, $x, $y, $code, $textColor);

但这样会降低验证码的美观度和防破解能力。

Ai作答

📣 商家广告


Ai评估

中国域名

vps

公司

店名


0

IP地址: 106.164.247.232

搜索次数: 29

提问时间: 2025-12-17 00:56:15

🛒 域名购买

❓️ 热门提问

🌐 域名评估

最新挖掘

🖌 热门作画

🤝 关于我们

🗨 加入群聊

🔗 友情链接

🧰 站长工具
📢

温馨提示

本站所有 问答 均由Ai自动分析整理,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。

👉

技术支持

本站由 🟢 豌豆Ai 提供技术支持,使用的最新版: 豌豆Ai站群搜索引擎系统 V.25.10.25 搭建本站。

上一篇 57305 57306 57307 下一篇