php实现获取验证码
使用GD库生成验证码
在PHP中,GD库是生成验证码图像的常用工具。以下是一个基本实现:
<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
for ($i = 0; $i < strlen($code); $i++) {
$color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, 20, rand(-30, 30), 20 + $i * 25, 30, $color, 'arial.ttf', $code[$i]);
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
添加干扰元素增强安全性
为了提高验证码的安全性,可以添加干扰线和干扰点:
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$color = 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), $color);
}
// 添加干扰点
for ($i = 0; $i < 200; $i++) {
$color = imagecolorallocate($image, rand(150, 250), rand(150, 250), rand(150, 250));
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
使用Composer包简化实现
可以使用现成的Composer包如gregwar/captcha简化验证码生成:

安装包:
composer require gregwar/captcha
使用示例:

<?php
require 'vendor/autoload.php';
session_start();
$builder = new Gregwar\Captcha\CaptchaBuilder;
$builder->build();
$_SESSION['captcha'] = $builder->getPhrase();
header('Content-type: image/jpeg');
$builder->output();
?>
验证码验证逻辑
在表单提交后验证验证码:
<?php
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
// 验证码正确
} else {
// 验证码错误
}
unset($_SESSION['captcha']); // 验证后销毁
?>
增加验证码难度
可以通过以下方式增加验证码难度:
// 使用更复杂的字符集
$chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
// 增加字符数量
$length = 6; // 代替之前的4个字符
// 使用扭曲变形
$builder->setDistortion(true);
注意事项
确保服务器已安装GD库,可通过phpinfo()检查。对于字体文件,确保路径正确或使用系统字体。验证码生成脚本应单独保存为PHP文件,通过img标签引用:
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()">






