php验证码如何实现
使用GD库生成图像验证码
安装GD库确保PHP环境已启用GD库扩展,可通过phpinfo()检查。若未安装,需在php.ini中取消extension=gd的注释并重启服务。
创建画布与背景色
通过imagecreatetruecolor()创建指定宽高的画布,使用imagecolorallocate()设置背景色和文本颜色:
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 240, 240, 240);
imagefill($image, 0, 0, $bgColor);
生成随机字符串
使用rand()或mt_rand()生成4-6位随机字符,通常包含数字和字母:
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = substr(str_shuffle($chars), 0, 5);
$_SESSION['captcha'] = $code; // 存储到Session
绘制干扰元素
添加干扰线或噪点增强安全性:
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
}
输出图像
设置HTTP头并输出PNG格式图像:
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
验证用户输入
表单提交后比对Session中的验证码:
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo '验证成功';
} else {
echo '验证码错误';
}
unset($_SESSION['captcha']); // 销毁Session
使用第三方库(如Gregwar/Captcha)
通过Composer安装简化开发:
composer require gregwar/captcha
生成验证码并嵌入表单:
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
echo '<img src="' . $builder->inline() . '" />';
安全性增强措施
- 限制验证码有效期(如5分钟过期)
- 禁止同一验证码重复使用
- 使用扭曲变形字体或动态滤镜(如
imagettftext()搭配TTF字体) - 前端限制频繁刷新请求
完整示例代码
// captcha.php
session_start();
$image = imagecreatetruecolor(100, 30);
$bg = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg);
$text = substr(md5(uniqid()), 0, 5);
$_SESSION['captcha'] = $text;
$color = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 30, 8, $text, $color);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
表单页调用方式:
<img src="captcha.php" />
<input type="text" name="captcha" required>






