php 实现验证码
生成验证码图片
使用 PHP 的 GD 库创建验证码图片,生成随机字符串并绘制到图片上:
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
$font = 'path/to/font.ttf'; // 替换为实际字体文件路径
for ($i = 0; $i < 4; $i++) {
$textColor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, 20, rand(-30, 30), 10 + $i * 30, 30, $textColor, $font, $code[$i]);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
添加干扰元素
增加干扰线和噪点提高安全性:
// 添加干扰线
for ($i = 0; $i < 5; $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);
}
// 添加噪点
for ($i = 0; $i < 200; $i++) {
$pixelColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $pixelColor);
}
前端调用验证码
在 HTML 中显示验证码图片并设置点击刷新:

<img src="captcha.php" id="captcha" onclick="this.src='captcha.php?'+Math.random()">
<input type="text" name="captcha" placeholder="输入验证码">
验证用户输入
在表单提交时验证用户输入的验证码:
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$userInput = strtolower(trim($_POST['captcha']));
$captcha = strtolower($_SESSION['captcha']);
if ($userInput === $captcha) {
echo '验证码正确';
} else {
echo '验证码错误';
}
}
提高安全性措施
增加验证码有效期限制和大小写不敏感验证:

// 在生成验证码时记录时间
$_SESSION['captcha_time'] = time();
// 验证时检查有效期(5分钟)
if (time() - $_SESSION['captcha_time'] > 300) {
echo '验证码已过期';
}
使用 Composer 包
对于更复杂的需求,可以考虑使用专业验证码库:
composer require gregwar/captcha
使用示例:
require 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-Type: image/jpeg');
$builder->output();





