php 实现验证码
使用 PHP 生成验证码
验证码(CAPTCHA)用于防止自动化脚本提交表单,以下是几种常见的 PHP 实现方法。
使用 GD 库生成图片验证码
GD 库是 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 = 6;
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
$font = 'path/to/font.ttf'; // 使用真实字体文件路径
for ($i = 0; $i < $length; $i++) {
$color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
imagettftext($image, 20, rand(-30, 30), 10 + $i * 20, 30, $color, $font, $code[$i]);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
添加干扰元素
为提高安全性,可以添加干扰线或干扰点。

// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$color = 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), $color);
}
// 添加干扰点
for ($i = 0; $i < 100; $i++) {
$color = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
验证用户输入
在表单提交后验证用户输入的验证码。
<?php
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
unset($_SESSION['captcha']); // 验证后销毁
?>
使用 Composer 包
对于更复杂的需求,可以使用现成的 Composer 包,如 gregwar/captcha。

安装包:
composer require gregwar/captcha
使用示例:
<?php
require 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-Type: image/jpeg');
$builder->output();
?>
验证时比较 $_SESSION['phrase'] 与用户输入。
安全注意事项
- 验证码应包含大小写字母和数字,避免使用易混淆字符(如 0 和 O)
- 验证码应在服务器端生成并存储,使用后立即销毁
- 考虑限制验证码尝试次数防止暴力破解
- 对于重要操作,可使用更复杂的验证码类型(如数学题、行为验证等)
这些方法提供了从基础到进阶的 PHP 验证码实现方案,可根据实际需求选择适合的方式。





