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 = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = substr(str_shuffle($chars), 0, 6);
$_SESSION['captcha'] = $code;
添加干扰元素增强安全性:
for($i=0; $i<200; $i++) {
$pixelColor = imagecolorallocate($image, rand(0,255), rand(0,255), rand(0,255));
imagesetpixel($image, rand()%$width, rand()%$height, $pixelColor);
}
for($i=0; $i<5; $i++) {
$lineColor = imagecolorallocate($image, rand(0,255), rand(0,255), rand(0,255));
imageline($image, rand()%$width, rand()%$height, rand()%$width, rand()%$height, $lineColor);
}
输出验证码图像:
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
验证码验证处理
创建验证页面验证用户输入:

session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$userCode = strtoupper(trim($_POST['captcha']));
if($userCode === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
unset($_SESSION['captcha']);
}
高级安全增强措施
使用更复杂的字体和变形技术:
$fontFile = 'path/to/font.ttf';
for($i=0; $i<strlen($code); $i++) {
$charColor = imagecolorallocate($image, rand(0,100), rand(0,100), rand(0,100));
$angle = rand(-10, 10);
$x = 20 + $i * 20;
$y = 30;
imagettftext($image, 20, $angle, $x, $y, $charColor, $fontFile, $code[$i]);
}
添加扭曲效果:

function waveImage($image, $width, $height) {
$newImage = imagecreatetruecolor($width, $height);
for($x=0; $x<$width; $x++) {
for($y=0; $y<$height; $y++) {
$sy = $y + (sin($x/10) * 3);
if($sy >= 0 && $sy < $height) {
$color = imagecolorat($image, $x, $sy);
imagesetpixel($newImage, $x, $y, $color);
}
}
}
return $newImage;
}
使用第三方库
考虑使用更专业的验证码库如:
- Gregwar/Captcha
- mewebstudio/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();
这些方法提供了从基础到高级的PHP验证码实现方案,可根据项目安全需求选择适当方案。





