php登录验证码实现
实现PHP登录验证码的方法
生成验证码图片
使用PHP的GD库创建验证码图片。创建一个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;
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
// 绘制验证码文字
$textColor = imagecolorallocate($image, 0, 0, 0);
$font = 'path/to/font.ttf'; // 使用自定义字体更安全
for ($i = 0; $i < $length; $i++) {
$angle = rand(-10, 10);
$x = 20 + $i * 25;
$y = 30;
imagettftext($image, 20, $angle, $x, $y, $textColor, $font, $code[$i]);
}
// 添加干扰元素
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);
?>
在HTML表单中显示验证码
在登录表单中添加验证码显示区域:

<form action="login.php" method="post">
<label>用户名: <input type="text" name="username"></label>
<label>密码: <input type="password" name="password"></label>
<label>验证码: <input type="text" name="captcha"></label>
<img src="captcha.php" alt="验证码" onclick="this.src='captcha.php?'+Math.random()">
<button type="submit">登录</button>
</form>
验证用户输入
在登录处理文件(如login.php)中验证验证码:

<?php
session_start();
$userCaptcha = isset($_POST['captcha']) ? strtoupper(trim($_POST['captcha'])) : '';
$validCaptcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : '';
if ($userCaptcha !== $validCaptcha) {
die('验证码错误');
}
// 验证通过后清除session中的验证码
unset($_SESSION['captcha']);
// 继续处理用户名和密码验证
// ...
?>
增强安全性措施
使用更复杂的验证码生成方式提高安全性:
// 在captcha.php中增加以下代码
$code = substr(str_shuffle(str_repeat('ABCDEFGHJKLMNPQRSTUVWXYZ23456789', 5)), 0, $length);
$_SESSION['captcha'] = md5(strtolower($code) . 'your_salt_here');
// 在login.php中验证时
$userInput = strtolower(trim($_POST['captcha']));
$storedCode = $_SESSION['captcha'];
if (md5($userInput . 'your_salt_here') !== $storedCode) {
die('验证码错误');
}
防止暴力破解
限制验证码尝试次数:
// 在login.php开头添加
session_start();
if (!isset($_SESSION['attempts'])) {
$_SESSION['attempts'] = 0;
}
$_SESSION['attempts']++;
if ($_SESSION['attempts'] > 3 && $userCaptcha !== $validCaptcha) {
die('尝试次数过多,请刷新页面重试');
}
这些方法组合使用可以有效实现PHP登录验证码功能,提高系统安全性。验证码图片生成后存储在session中,用户提交表单时进行比对验证。通过添加干扰元素、使用自定义字体和限制尝试次数等措施,可以进一步增强验证码的安全性。






