代码改变世界

PHP实现验证码

2012-01-12 17:35  少毅  阅读(214)  评论(0编辑  收藏  举报

通过PHP实现验证码的生成,大概原理如下:

首先利用在写好的验证码字典中随机获取指定数量的随机码,函数如下:

//产生随机字符串
function randStr($len) {
$chars='ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
$string="";
while(strlen($string)<$len){
$string.=substr($chars,(mt_rand()%strlen($chars)),1);
}
return $string;
}

$char为验证码字典

通过while循环,每次在字典中随机获取一个码,直到串联成指定个数的码

利用mt_rand()函数随机返回一个整数

生产验证码字符串后,使用GD库中的一些图形操作函数,实现验证码的显示,代码如下:

$type = 'gif';
$width= 60;
$height= 30;
header("Content-type: image/".$type); //设置类型
srand((double)microtime()*1000000);
$randval = randStr(4); //获取随机码
if($type!='gif' && function_exists('imagecreatetruecolor')){
$im = @imagecreatetruecolor($width,$height);
}else{
$im = @imagecreate($width,$height);
}


$backColor = ImageColorAllocate($im,223,215,125);//背景色
$borderColor = ImageColorAllocate($im, 100,100,100);//边框色
$pointColor = ImageColorAllocate($im, 255, 170, 255);//干扰点颜色
$stringColor = ImageColorAllocate($im, 0,0,0); //验证码文字颜色

@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);//背景填充
@imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor); //边框填充
  //产生干扰点

  for($i=0;$i<=100;$i++){
     $pointX = rand(2,$width-2);
     $pointY = rand(2,$height-2);
     @imagesetpixel($im, $pointX, $pointY, $pointColor);
  }
  //产生验证码

  @imagestring($im, 5, 10, 5, $randval, $stringColor);
  $ImageFun='Image'.$type;
  $ImageFun($im);
  @ImageDestroy($im);