php登录验证码实现
验证码生成与显示
使用PHP的GD库生成验证码图片,并将验证码字符串存入Session以便后续验证。以下是一个基础实现示例:
// 生成验证码
session_start();
$width = 120;
$height = 40;
$image = imagecreate($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
// 生成随机字符串
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$captcha = substr(str_shuffle($chars), 0, 6);
$_SESSION['captcha'] = $captcha;
// 绘制干扰线
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">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<input type="text" name="captcha" placeholder="验证码">
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()">
<button type="submit">登录</button>
</form>
验证码校验处理
在登录处理页面验证用户输入的验证码:
session_start();
if (strtolower($_POST['captcha']) !== strtolower($_SESSION['captcha'])) {
die('验证码错误');
}
// 验证通过后清除session中的验证码
unset($_SESSION['captcha']);
// 继续处理登录逻辑...
增强安全性措施
添加以下安全增强措施:

- 设置验证码有效期(如5分钟)
- 限制验证码尝试次数
- 使用更复杂的扭曲变形字体
// 在生成验证码时添加时间戳
$_SESSION['captcha_time'] = time();
$_SESSION['captcha'] = $captcha;
// 验证时检查时间
if (time() - $_SESSION['captcha_time'] > 300) {
die('验证码已过期');
}
使用Composer包实现
对于更复杂的需求,可以考虑使用专业的验证码生成库:
composer require gregwar/captcha
使用示例:
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-type: image/jpeg');
$builder->output();
这些方法提供了从基础到进阶的PHP验证码实现方案,可根据项目需求选择合适的实现方式。






