php实现验证码
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 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charLength = strlen($chars);
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, $charLength - 1)];
}
$_SESSION['captcha'] = $code;
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, 'arial.ttf', $code[$i]);
}
for ($i = 0; $i < 50; $i++) {
$pixelColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $pixelColor);
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
使用HTML表单显示验证码
在HTML页面中显示生成的验证码图片:

<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()" style="cursor:pointer" title="点击刷新验证码">
验证用户输入
验证用户提交的验证码是否正确:

<?php
session_start();
if ($_POST['captcha'] == $_SESSION['captcha']) {
echo '验证码正确';
} else {
echo '验证码错误';
}
?>
增加干扰线和扭曲效果
为了增强安全性,可以添加干扰线和扭曲效果:
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($image, rand(150, 255), rand(150, 255), rand(150, 255));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
// 扭曲效果
$distortionImage = imagecreatetruecolor($width, $height);
imagefill($distortionImage, 0, 0, $bgColor);
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$newX = $x + sin($y / 10) * 5;
$newY = $y + sin($x / 10) * 5;
$color = imagecolorat($image, $x, $y);
imagesetpixel($distortionImage, $newX, $newY, $color);
}
}
使用Composer包
可以使用现成的Composer包来简化验证码生成:
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();
?>
注意事项
- 确保服务器已安装GD库
- 验证码应包含大小写字母和数字组合
- 验证码应在会话中存储
- 验证码图片应设置适当的过期头
- 可以考虑限制验证码尝试次数防止暴力破解





