PHP验证码的制作

<?php
if(!isset($_SESSION)){ //判断session是否开启
session_start();
}

/*
*随机生成验证码函数
*param $m:验证码位数 默认值为4
*param $type:验证码类型 0:数学 1:数字+小写字母 2:数字+大小写字母
*/
function getCode($m=4,$type=0){
$str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$t = array(9,35,strlen($str)-1);//t[0]:0-9:数字 ;t[2]:0-35:数字+小写字母 ;t[2]:0-最后:所有字符;
$c ="";
for($i=0; $i<$m; $i++){
$c.=$str[rand(0,$t[$type])];
}
return $c;
}

//1.获取验证码字符
$num=4;
$str = getCode($num,0);
$_SESSION['verifycode'] = $str;
//2.创建画布
$width=$num*20;
$height=30;
$im = imagecreatetruecolor($width,$height);
$c = imagecolorallocate($im,111,0,55);
$rect = imagecolorallocate($im,20,0,190);
$bg = imagecolorallocate($im,200,200,200);
//3.开始绘制
imagefill($im,0,0,$bg);//背景色
imagerectangle($im,0,0,$width-1,$height-1,$rect);//边框
//4.添加干扰点
for($i=0; $i<200; $i++){
$c = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($im,rand(0,$width),rand(0,$height),$c);
}
//5.添加干扰线
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,$heigth),$c);
}
//6.绘制验证码内容
for($i=0; $i<$num; $i++){
imagettftext($im,18,8+(10*$i),8+(18*$i),24,$c,"plantc.ttf",$str[$i]);//plantc.ttf为字体文件,根据实际路径设置
}
//7.输出验证码图形
header("Content-Type:image/png");
imagepng($im);
imagedestroy($im);
?>

posted on 2013-11-06 21:19  为人民服务  阅读(214)  评论(0编辑  收藏  举报