PHP 验证码生成程序:抗破解,带背景噪点
以下是一个简单的 PHP 验证码程序,使用随机生成的字符和背景图中的噪点来增加验证码的安全性:
<?php
session_start();
$width = 120;
$height = 40;
$length = 6; // 验证码长度
$fontSize = 20;
// 随机生成验证码
$code = '';
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[mt_rand(0, strlen($chars) - 1)];
}
// 将验证码存入session
$_SESSION['captcha'] = $code;
// 创建画布并填充背景色
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
// 添加噪点
for ($i = 0; $i < $width * $height / 20; $i++) {
$color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($image, mt_rand(0, $width - 1), mt_rand(0, $height - 1), $color);
}
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imageline($image, 0, mt_rand(0, $height), $width, mt_rand(0, $height), $color);
}
// 添加验证码文本
$fontFile = 'arial.ttf';
$textColor = imagecolorallocate($image, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
$angle = mt_rand(-10, 10);
$x = mt_rand(10, $width - $fontSize * $length);
$y = mt_rand($fontSize, $height - $fontSize);
imagettftext($image, $fontSize, $angle, $x, $y, $textColor, $fontFile, $code);
// 输出图像
header('Content-type: image/png');
imagepng($image);
// 清理资源
imagedestroy($image);
?>
该程序使用PHP的GD库创建验证码图像,并在图像中添加随机生成的字符、干扰线和噪点。验证码的长度、字体大小、字体文件等可以根据需要进行自定义。验证码的值存储在session中,供后续验证使用。
原文地址: https://www.cveoy.top/t/topic/nQNj 著作权归作者所有。请勿转载和采集!