探索 PHP 生成验证码:从基础图形验证到安全优化
文章最后更新时间:2025年12月11日
验证码是防范恶意注册、暴力登录的重要手段,PHP 结合 GD 库可快速生成图形验证码。本文从基础图形验证码实现入手,讲解如何提升验证码的安全性和易用性。

一、基础实现:生成 4 位数字验证码
<?php
// 开启会话(存储验证码用于验证)
session_start();
// 创建画布
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
// 设置颜色
$bgColor = imagecolorallocate($image, 255, 255, 255);
$fontColor = imagecolorallocate($image, 0, 0, 0);
$lineColor = imagecolorallocate($image, 150, 150, 150);
// 填充背景
imagefill($image, 0, 0, $bgColor);
// 绘制干扰线
for ($i = 0; $i < 5; $i++) {
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
// 生成4位随机验证码
$code = rand(1000, 9999);
$_SESSION['verify_code'] = $code;
// 绘制验证码文字
imagestring($image, 5, rand(30, 80), rand(10, 25), $code, $fontColor);
// 输出图片
header('Content-Type: image/png');
imagepng($image);
// 销毁资源
imagedestroy($image);
?>二、验证验证码(前端 + 后端)
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$inputCode = trim($_POST['code'] ?? '');
if ($inputCode === $_SESSION['verify_code']) {
echo "验证码正确!";
} else {
echo "验证码错误!";
}
// 验证后销毁验证码,防止重复使用
unset($_SESSION['verify_code']);
}
?>
<!-- 前端表单 -->
<form method="post">
<img src="verify_code.php" onclick="this.src='verify_code.php?'+Math.random()" alt="验证码">
<input type="text" name="code" placeholder="输入验证码">
<button type="submit">验证</button>
</form>总结
文章版权声明:除非注明,否则均为Dark零点博客原创文章,转载或复制请以超链接形式并注明出处。

