php实现动态验证码
实现动态验证码的步骤
生成验证码图片
使用GD库创建验证码图片,设置背景色、文字颜色和干扰元素。
// 创建画布
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
// 设置背景色和文字颜色
$bgColor = imagecolorallocate($image, 240, 240, 240);
$textColor = imagecolorallocate($image, 0, 0, 0);
// 填充背景
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);
// 生成随机验证码
$code = substr(md5(uniqid()), 0, 6);
$_SESSION['captcha'] = $code;
// 绘制验证码文字
imagestring($image, 5, 30, 12, $code, $textColor);
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
// 输出图片
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
创建验证码显示页面
创建一个PHP文件专门输出验证码图片,例如captcha.php。
在HTML中调用验证码
在表单页面中通过img标签引用验证码生成脚本。

<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()" style="cursor:pointer" title="点击刷新验证码">
<input type="text" name="captcha" placeholder="请输入验证码">
验证用户输入
在表单处理页面验证用户输入的验证码是否正确。
session_start();
if ($_POST['captcha'] !== $_SESSION['captcha']) {
die('验证码错误');
}
增加安全性措施
验证码应设置有效期,通常为5-10分钟。

$_SESSION['captcha_time'] = time();
// 验证时检查时间
if (time() - $_SESSION['captcha_time'] > 600) {
die('验证码已过期');
}
提高验证码复杂度
可以使用随机字体、扭曲变形或彩色文字增强安全性。
// 使用TrueType字体
$font = 'arial.ttf';
imagettftext($image, 20, rand(-10, 10), 20, 30, $textColor, $font, $code);
// 扭曲变形
imagefilter($image, IMG_FILTER_WAVE, rand(1, 5), rand(10, 50));
防止暴力破解
限制验证码尝试次数,超过次数后锁定或要求重新获取验证码。
if (!isset($_SESSION['attempts'])) {
$_SESSION['attempts'] = 0;
}
$_SESSION['attempts']++;
if ($_SESSION['attempts'] > 3) {
die('尝试次数过多,请刷新验证码');
}






