php验证码的实现
PHP验证码的实现方法
验证码(CAPTCHA)用于防止自动化脚本提交表单,以下为PHP生成验证码的常见方法:

使用GD库生成图片验证码
<?php
session_start();
header('Content-Type: image/png');
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$captcha = '';
for ($i = 0; $i < 4; $i++) {
$char = $chars[rand(0, strlen($chars) - 1)];
$captcha .= $char;
$textColor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, 20, rand(-30, 30), 10 + $i * 30, 30, $textColor, 'arial.ttf', $char);
}
$_SESSION['captcha'] = $captcha;
for ($i = 0; $i < 10; $i++) {
$lineColor = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
imagepng($image);
imagedestroy($image);
?>
前端调用验证码图片
<img src="captcha.php" id="captcha" onclick="this.src='captcha.php?'+Math.random()">
<input type="text" name="captcha" required>
验证用户输入
session_start();
if ($_POST['captcha'] !== $_SESSION['captcha']) {
die('验证码错误');
}
unset($_SESSION['captcha']);
使用第三方库
安装Gregwar/Captcha库:
composer require gregwar/captcha
使用示例:
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-type: image/jpeg');
$builder->output();
提高安全性措施
- 设置验证码有效期(如5分钟)
- 限制验证码尝试次数
- 使用更复杂的干扰元素(如扭曲文字、背景噪点)
- 考虑使用reCAPTCHA等Google提供的服务
验证码实现应考虑用户体验与安全性的平衡,过于复杂的验证码可能降低用户体验,而过于简单的验证码则容易被破解。







