/**
说明: 验证码生成类,支持生成Gif图片验证码(带噪点,干扰线,网格,随机色背景,随机自定义字体,倾斜,Gif动画)
服务端:
$mod = strtolower(isset($_REQUEST["mod"]) ? $_REQUEST["mod"] : "");
if($mod == "code"){
echo SecurityCode::Draw(4, 1, 120, 30, 5, 10, 100, "secode");
die();
}
调用: <img src="https://www.jb51.net/getcode.php?mod=code">
验证:
$reqCode = strtolower(isset($_REQUEST["secode"]) ? $_REQUEST["secode"] : ""); //请求的验证码
$sessionCode = strtolower(isset($_SESSION["secode"]) ? $_SESSION["secode"] : ""); //会话生成的验证码
if($reqCode != $sessionCode){
echo "安全验证码错误!";
die();
}
*/
$mod = strtolower(isset($_REQUEST["mod"]) ? $_REQUEST["mod"] : "");
if ($mod == "code") {
echo SecurityCode::Draw(4, 15, 100, 27, 10, 2, 100, "secode");
die();
}
//安全验证码类
class SecurityCode {
private static $Debug = 0;
private static $Code = '';
private static $Chars = 'bcdefhkmnrstuvwxyABCDEFGHKMNPRSTUVWXY34568';
//private static $Chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890';
private static $TextGap = 20;
private static $TextMargin = 5;
private static $FontFilePath = "static/font/"; //相对地本代码文件的位置
private static $FontFileName =array("3.ttf");// array("1.ttf", "2.ttf", "3.ttf", "4.ttf", "5.ttf", "6.ttf", "7.ttf", "8.ttf"); //
private static $Img = 'GIF89a'; //GIF header 6 bytes
private static $BUF = Array();
private static $LOP = 0;
private static $DIS = 2;
private static $COL = -1;
private static $IMG = -1;
/**
生成GIF图片验证
@param int $L 验证码长度
@param int $F 生成Gif图的帧数
@param int $W 宽度
@param int $H 高度
@param int $MixCnt 干扰线数
@param int $lineGap 网格线间隔
@param int $noisyCnt 澡点数
@param int $sessionName 验证码Session名称
*/
public static function Draw($L = 4, $F = 1, $W = 150, $H = 30, $MixCnt = 2, $lineGap = 0, $noisyCnt = 10, $sessionName = "Code") {
ob_start();
ob_clean();
for ($i = 0; $i < $L; $i++) {
self::$Code .= SubStr(self::$Chars, mt_rand(0, strlen(self::$Chars) - 1), 1);
}
if (!isset($_SESSION))
session_start();
$_SESSION[$sessionName] = strtolower(self::$Code);
$bgRGB = array(rand(0, 255), rand(0, 255), rand(0, 255));
//生成一个多帧的GIF动画
for ($i = 0; $i < $F; $i++) {
$img = ImageCreate($W, $H);
//背景色
$bgColor = imagecolorallocate($img, $bgRGB[0], $bgRGB[1], $bgRGB[2]);
ImageColorTransparent($img, $bgColor);
unset($bgColor);
//添加噪点
$maxNoisy = rand(0, $noisyCnt);
$noisyColor = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
for ($k = 0; $k <= $maxNoisy; $k++) {
imagesetpixel($img, rand(0, $W), rand(0, $H), $noisyColor);
}
//添加网格
if ($lineGap > 0) {
for ($m = 0; $m < ($W / $lineGap); $m++) { //竖线
imageline($img, $m * $lineGap, 0, $m * $lineGap, $H, $noisyColor);
}
for ($n = 0; $n < ($H / $lineGap); $n++) { //横线
imageline($img, 0, $n * $lineGap, $W, $n * $lineGap, $noisyColor);
}
}
unset($noisyColor);