PHP实现验证码

通过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);

 

转载于:https://www.cnblogs.com/chenshaoyi/archive/2012/01/12/2320875.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值