php如何实现验证码
使用GD库生成验证码
PHP的GD库可以用于生成图像验证码。以下是一个基本实现示例:
<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = 6;
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
$font = 5;
$x = 10;
$y = 15;
for ($i = 0; $i < $length; $i++) {
$textColor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagestring($image, $font, $x, $y, $code[$i], $textColor);
$x += 20;
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
添加干扰元素增强安全性
为提高验证码安全性,可以添加干扰线和噪点:

// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($image, rand(100, 255), rand(100, 255), rand(100, 255));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
// 添加噪点
for ($i = 0; $i < 100; $i++) {
$pixelColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $pixelColor);
}
使用TrueType字体提升视觉效果
使用TTF字体可以生成更美观的验证码:

$fontFile = 'path/to/font.ttf';
for ($i = 0; $i < $length; $i++) {
$angle = rand(-30, 30);
$textColor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, 20, $angle, $x, $y, $textColor, $fontFile, $code[$i]);
$x += 25;
}
验证用户输入
在表单处理页面验证用户输入的验证码:
session_start();
if (strtolower($_POST['captcha']) == strtolower($_SESSION['captcha'])) {
echo "验证码正确";
} else {
echo "验证码错误";
}
unset($_SESSION['captcha']);
使用第三方库简化开发
可以考虑使用现成的验证码库如Gregwar/Captcha:
require_once 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-type: image/jpeg');
$builder->output();
安全注意事项
验证码应区分大小写或统一转换为小写比较 每次验证后应立即销毁session中的验证码值 限制验证码尝试次数防止暴力破解 考虑添加过期时间限制验证码有效性






