php如何实现验证码
生成验证码图片
使用 PHP 的 GD 库创建验证码图片。通过 imagecreatetruecolor() 函数创建一个空白画布,设置背景色和文本颜色。利用 imagestring() 或 imagettftext() 函数将随机生成的验证码字符串绘制到图片上。
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$textColor = imagecolorallocate($image, 0, 0, 0);
$code = substr(md5(uniqid()), 0, 6);
imagestring($image, 5, 30, 12, $code, $textColor);
添加干扰元素
为了提高安全性,可以在验证码图片中添加干扰线或噪点。使用 imageline() 函数绘制随机线条,或通过循环使用 imagesetpixel() 添加噪点。
for ($i = 0; $i < 5; $i++) {
$lineColor = 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), $lineColor);
}
输出验证码图片
通过 header() 函数设置正确的 Content-Type,并使用 imagepng() 或 imagejpeg() 函数输出图片。确保在输出后调用 imagedestroy() 释放内存。
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
存储验证码
将生成的验证码字符串存储到 Session 中,以便后续验证。使用 session_start() 开启 Session,并将验证码存入 $_SESSION 数组。
session_start();
$_SESSION['captcha'] = $code;
验证用户输入
在表单提交后,比较用户输入的验证码与 Session 中存储的值。使用 strtolower() 或 strtoupper() 进行大小写不敏感的比较。
session_start();
if (isset($_POST['captcha']) && strtolower($_POST['captcha']) === strtolower($_SESSION['captcha'])) {
echo "验证码正确";
} else {
echo "验证码错误";
}
使用 Composer 包
对于更复杂的验证码需求,可以使用第三方库如 gregwar/captcha。通过 Composer 安装后,可以快速生成验证码图片并验证输入。
require_once 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-Type: image/jpeg');
$builder->output();






