php验证码实现
验证码生成与验证的实现
在PHP中实现验证码功能通常包括生成验证码图片和验证用户输入两部分。以下是完整的实现方法:
生成验证码图片
创建名为captcha.php的文件,用于生成验证码图像:
<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
// 生成随机验证码
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$length = 4;
$captcha = '';
for ($i = 0; $i < $length; $i++) {
$captcha .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $captcha;
// 添加干扰元素
for ($i = 0; $i < 5; $i++) {
$color = 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), $color);
}
// 绘制验证码文字
for ($i = 0; $i < $length; $i++) {
$color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
$fontSize = rand(16, 24);
$x = ($width / $length) * $i + rand(5, 10);
$y = rand($fontSize, $height - 5);
imagettftext($image, $fontSize, rand(-15, 15), $x, $y, $color, 'arial.ttf', $captcha[$i]);
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
在HTML中显示验证码
在表单页面中插入验证码图片:
<form action="submit.php" method="post">
<img src="captcha.php" alt="CAPTCHA" onclick="this.src='captcha.php?'+Math.random()">
<input type="text" name="captcha" required>
<button type="submit">提交</button>
</form>
验证用户输入
创建submit.php文件处理表单验证:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$userCaptcha = strtoupper(trim($_POST['captcha']));
$sessionCaptcha = $_SESSION['captcha'];
if ($userCaptcha === $sessionCaptcha) {
echo "验证码正确";
} else {
echo "验证码错误";
}
unset($_SESSION['captcha']); // 验证后清除
}
?>
安全性增强措施
使用更复杂的验证码字符集,避免使用易混淆的字符如0和O。增加验证码过期时间限制:
$_SESSION['captcha_time'] = time();
// 验证时检查是否超过5分钟
if (time() - $_SESSION['captcha_time'] > 300) {
echo "验证码已过期";
}
对于生产环境,考虑使用Google reCAPTCHA等第三方服务提供更强大的验证码保护。







