php创建验证码

来源:互联网 发布:插画师软件 编辑:程序博客网 时间:2024/05/22 06:15

小弟最近在学网站后台,经过一下午的艰苦奋战以及各种百度,终于搞定验证码这个大问题(各路大神级别的请无视)。此程序运行需加载bg库。

环境:xampp for windows

下面献上代码:

<?php
$length  = 4;
$code = loadCode();
$width = $length*25;
$height = 30;
//创建一个画布
$im=imagecreatetruecolor($width,$height);
$c[]=imagecolorallocate($im,255,0,0);//定义一个颜色(画笔)
$c[]=imagecolorallocate($im,22,122,43);
$c[]=imagecolorallocate($im,181,26,65);
$c[]=imagecolorallocate($im,73,29,226);
$c[]=imagecolorallocate($im,16,29,186);
$c[]=imagecolorallocate($im,55,206,206);
$c[]=imagecolorallocate($im,33,88,45);
$c[]=imagecolorallocate($im,0,0,255);
$bg[]=imagecolorallocate($im,220,220,220);
$bg[]=imagecolorallocate($im,169,221,226);
$bg[]=imagecolorallocate($im,169,173,243);
$bg[]=imagecolorallocate($im,234,179,189);

//2.开始绘画
imagefill($im,0,0,$bg[rand(0,count($bg)-1)]);

//绘制验证码
for($i=0; $i<$length; $i++){
imagettftext($im,20,rand(-30,30),8+$i*20,25,$c[rand(0,count($c)-1)],"./simhei.ttf",$code[$i]);
}

//./simhei.ttf为字体,可以在C:\Windows\Fonts目录下选择自己需要的

//添加干扰点
for($i=0; $i<100; $i++){
$c = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($im,rand(0,$width),rand(0,$height),$c);
}

//添加干扰线
for($i=0; $i<5; $i++){
$c = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imageline($im,rand(0,$width),rand(0,$height),rand(0,$width),rand(0,$height),$c);
}

//输出绘画图像
header("Content-type:image/png");//指定头部信息类型(乱码问题大部分都是因为这句话没对,或者没加)
imagepng($im); //输出图片

//释放资源
imagedestroy($im);

//随机获取验证码值函数
function loadCode($length=4, $type=2){
$str = "0123456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//根据类型判断随机长度
$m = 9;
if($type == 2){
$m = 33;
}
else if($type == 3){
$m = strlen($str)-1;
}
$c = "";
//开始随机验证码
for($i=0; $i<$length; $i++){
$c.=$str[rand(0,$m)];
}
return $c;
}
?>

0 0