1.得到验证码字符串
/** 得到验证吗字符串
* @param int $type
* @param int $length
* @return string
*/
function getVerifycode($type = 1,$length = 4){
/*
* 根据$type的值生成不同类型的验证码
* 根据$length的值生成不同长度的验证码
*
* $type == 1 纯数字
* $type == 2 纯字母
* $type == 3 字母数字混合
* */
if($type == 1){
$chars = join("",range(0,9));
}elseif($type == 2){
$chars = join("",array_merge(range("a","z"),range("A","Z")));
}elseif($type == 3){
$chars = join("",array_merge(range("A","Z"),range("a","z"),range(0,9)));
}else{
exit("验证码类型输入错误!");
}
if($length>strlen($chars)){
exit("验证码长度不够!");
}
$chars = str_shuffle($chars);
return substr($chars,0,$length);
}
2.生成验证码图片
function getVerifyimage($width = 80,$height = 30){
session_start();
$image=imagecreatetruecolor($width,$height);
$white=imagecolorallocate($image,255,255,255);
$black=imagecolorallocate($image,0,0,0);
$type=1;
$length=4;
imagefilledrectangle($image,1,1,$width-2,$height-2,$white);
$chars=getVerifycode($type,$length);
$session_name="verifycode";
$_SESSION[$session_name]=$chars;
for($i=0;$i<$length;$i++){
$size=mt_rand(14,18);
$x=5+$i*$size;
$y=mt_rand(2,15);
$color=imagecolorallocate($image,mt_rand(50,90),mt_rand(80,200),mt_rand(40,120));
$text=substr($chars,$i,1);
imagestring($image,$size,$x,$y,$text,$color);
}
for($i=0;$i<66;$i++){
imagesetpixel($image,mt_rand(0,$width-1),mt_rand(0,$height-1),$color);
}
for($i=0;$i<6;$i++){
imageline($image,mt_rand(0,$width-1),mt_rand(0,$width-1),mt_rand(0,$height-1),mt_rand(0,$height-1),$color);
}
header("content-type:image/gif");
imagegif($image);
imagedestroy($image);
}