php实现图形验证码
生成图形验证码
在PHP中,可以使用GD库生成图形验证码。GD库是一个开源的图像处理库,支持多种图像格式。
确保服务器已安装GD库,可以通过phpinfo()查看是否启用。以下是一个简单的图形验证码生成代码:
<?php
session_start();
$width = 100;
$height = 30;
$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, rand(14, 18), rand(-30, 30), 10 + $i * 20, 20, $textColor, 'arial.ttf', $code[$i]);
}
for ($i = 0; $i < 5; $i++) {
$lineColor = 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), $lineColor);
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
验证码使用
将上述代码保存为captcha.php,在HTML中通过img标签引用:
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()" style="cursor:pointer;" title="点击刷新验证码">
验证码验证
在表单提交后,通过session比对验证码:
session_start();
if ($_POST['captcha'] !== $_SESSION['captcha']) {
die('验证码错误');
}
增强安全性
为增加安全性,可以采取以下措施:
- 增加验证码字符长度
- 使用更复杂的字体和扭曲效果
- 添加背景干扰元素
- 限制验证码尝试次数
- 设置验证码过期时间
使用第三方库
对于更复杂的需求,可以考虑使用以下第三方库:
- Gregwar/Captcha:提供更丰富的验证码生成功能
- mewebstudio/Captcha:支持多种验证码类型
- Intervention/image:提供更强大的图像处理能力
这些库可以通过Composer安装,提供更简便的API和更丰富的功能。







